线程---同步(synchronized)

2021-07-15 07:08

阅读:712

标签:循环输出   run   end   catch   for   extends   control   stat   back   

实现线程同步的一种方式介绍:

思路:

    首先,需要被协调的类,先实现线程,并重写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 

  

线程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 

  

线程C:

public class C extends Thread{

	private Controller controller;
	
	C(Controller controller){
		this.controller = controller;
	}
	
	@Override
	public void run() {
		for (int i = 0; i 

 

输出:

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

 

线程---同步(synchronized)

标签:循环输出   run   end   catch   for   extends   control   stat   back   

原文地址:https://www.cnblogs.com/pecool/p/9536931.html

上一篇:JavaScript之图片操作1

下一篇:Js的执行


评论


亲,登录后才可以留言!