实现线程同步的一种方式介绍:
思路:
首先,需要被协调的类,先实现线程,并重写run方法
然后,在被协调的类中私有化控制器,控制器实例化,由构造器带入。
其次,由控制器对象具体负责调用。
举例:循环输出A/B/C
main:
public class Test { public static void main(String[] args) { Controller controller = new Controller(); new A(controller).start();; new B(controller).start();; new C(controller).start();; } }
控制器:
public class Controller { private int f=0; public synchronized void printA(){ if(f==0){ System.out.println("A"); f=1; notifyAll(); } try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void printB(){ if(f==1){ System.out.println("B"); f=2; notifyAll(); } try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void printC(){ if(f==2){ System.out.println("C"); f=0; notifyAll(); } try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
线程A:
public class A extends Thread{ private Controller controller; A(Controller controller){ this.controller = controller; } @Override public synchronized void run() { for (int i = 0; i < 10; i++) { controller.printA(); } } }
线程B:
public class B extends Thread{ private Controller controller; B(Controller controller){ this.controller = controller; } @Override public synchronized void run() { for (int i = 0; i < 10; i++) { controller.printB(); } } }
线程C:
public class C extends Thread{ private Controller controller; C(Controller controller){ this.controller = controller; } @Override public void run() { for (int i = 0; i < 10; i++) { controller.printC(); } } }
输出:
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
原文地址:https://www.cnblogs.com/pecool/p/9536931.html
时间: 2024-11-13 04:00:49