面试题:用三个线程按顺序循环打印 abc 三个字母,比如 abcabcabc

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/wjw521wjw521/article/details/88422512

揣摩出题人意图,应该希望你用wait notify notifyAll来一环套一环进行线程通信,从而按顺序循环打印abc,也就是说,打印了a就打印b然后打印c。

思路就是我们三个线程用同一把锁,刚开始,a线程获取锁,打印a,设置下一个打印b,并同时唤醒bc,这时候,bc线程都阻塞等待,如果c抢到了锁,进入代码执行,由于不符合条件,会wait(同时释放锁),直到b抢到锁,符合条件打印,如此,顺序执行下去。

代码如下:


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class ABCTest {
	static Object syn = new Object();
	public static String next = "a";



	public static void main(String[] args) {
		new ABCTest().print();
	}
	


	private void print(){
		ExecutorService service =  Executors.newFixedThreadPool(3);
		service.execute(new APrinThread());
		service.execute(new BPrinThread());
		service.execute(new CPrinThread());
		
	}

class APrinThread implements Runnable{
	
		@Override
	public void run() {
		while(true){
			synchronized (syn) {
				while(!"a".equals(next)){
					try {
						syn.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.print("a");
				next = "b";
				syn.notifyAll();
			}
				

			
							
		}
		
	}
	
	
}

//


class BPrinThread implements Runnable{
	

	@Override
	public void run() {
		while(true){
			synchronized (syn) {
				while(!"b".equals(next)){
					try {
						syn.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.print("b");
				next = "c";
				syn.notifyAll();
			}
				

			
							
		}
		
	}
	
	
}

//



class CPrinThread implements Runnable{
	
	
	@Override
	public void run() {
		while(true){
			synchronized (syn) {
				while(!"c".equals(next)){
					try {
						syn.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println("c");
				next = "a";
				syn.notifyAll();
			}
				

			
							
		}
		
	}
	
	
}
}



	
	

end

猜你喜欢

转载自blog.csdn.net/wjw521wjw521/article/details/88422512