线程---同步(synchronized)
2021-07-15 07:08
标签:循环输出 run end catch for extends control stat back 实现线程同步的一种方式介绍: 思路: 首先,需要被协调的类,先实现线程,并重写run方法 然后,在被协调的类中私有化控制器,控制器实例化,由构造器带入。 其次,由控制器对象具体负责调用。 举例:循环输出A/B/C main: 控制器: 线程A: 线程B: 线程C: 输出: A 线程---同步(synchronized) 标签:循环输出 run end catch for extends control stat back 原文地址:https://www.cnblogs.com/pecool/p/9536931.htmlpublic 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();
}
}
}
public class A extends Thread{
private Controller controller;
A(Controller controller){
this.controller = controller;
}
@Override
public synchronized void run() {
for (int i = 0; i
public class B extends Thread{
private Controller controller;
B(Controller controller){
this.controller = controller;
}
@Override
public synchronized void run() {
for (int i = 0; i
public class C extends Thread{
private Controller controller;
C(Controller controller){
this.controller = controller;
}
@Override
public void run() {
for (int i = 0; i
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
上一篇:JavaScript之图片操作1
下一篇:Js的执行