Questions d'entretien des fils - Les fils alternent dans l'ordre

Les fils alternent dans l'ordre

Écrivez un programme et démarrez 3 threads. Les ID de ces trois threads sont A, B et C. Chaque thread imprime son ID sur la console 10 fois et les résultats de sortie doivent être affichés dans l'ordre.

Par exemple: ABCABCABCABC ... une fois récursivement ...

public class TestABCLoop {
	public static void main(String[] args) {
		final ABCLoopDemo loop = new ABCLoopDemo();
		
		new Thread(new Runnable() {
			public void run() {
				for(int i=1;i<=20;i++){
					loop.loopA();
				}
			}
		},"A").start();
		
		new Thread(new Runnable() {
			public void run() {
				for(int i=1;i<=20;i++){
					loop.loopB();
				}
			}
		},"B").start();
		
		new Thread(new Runnable() {
			public void run() {
				for(int i=1;i<=20;i++){
					loop.loopC();
					System.out.println("---------第"+i+"轮-------------");
				}
			}
		},"C").start();
	}
}

class ABCLoopDemo{
	private int flag = 1; //打印标记
	private Lock l = new ReentrantLock();
	private Condition c1 = l.newCondition();
	private Condition c2 = l.newCondition();
	private Condition c3 = l.newCondition();
	
	public void loopA(){
		l.lock();
		try{
			//1. 判断
			if(flag!=1){
				c1.await();
			}
			
			//2. 打印
			System.out.println(Thread.currentThread().getName());	
			
			//3. 唤醒
			flag=2;
			c2.signal();	
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			l.unlock();
		}
	}
	public void loopB(){
		l.lock();
		try{
			//1. 判断
			if(flag!=2){
				c2.await();
			}
			
			//2. 打印
			System.out.println(Thread.currentThread().getName());	
			
			//3. 唤醒
			flag=3;
			c3.signal();	
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			l.unlock();
		}
	}
	public void loopC(){
		l.lock();
		try{
			//1. 判断
			if(flag!=3){
				c3.await();
			}
			
			//2. 打印
			System.out.println(Thread.currentThread().getName());	
			
			//3. 唤醒
			flag=1;
			c1.signal();	
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			l.unlock();
		}
	}
}

Je suppose que tu aimes

Origine blog.csdn.net/Java_lover_zpark/article/details/89470511
conseillé
Classement