使用thread實現打印ABCABCABC

1.描述

     最近在刷面試題,看到了一個很好玩的面試題,就是使用線程技術創建3個線程,分別打印A,B,C的線程,然後按順序打印ABC,連續打印3次。我感覺這個面試題挺有意思的就花了點時間,寫了一下,下面貼出代碼,如果有地方錯誤的請大神多多指點。


public class LockDemo3 {

	public static void main(String[] args) {
		new LockDemo3().doMain();
	}
	
	public void doMain(){
		Res res = new Res();
		
		ThreadA threadA = new ThreadA(res);
		ThreadB threadB = new ThreadB(res);
		ThreadC threadC = new ThreadC(res);
		
		threadA.start();
		threadB.start();
		threadC.start();
	}
	
	class Res{
		private int flag = 0;
		
	}
	class ThreadA extends Thread{
		
		private Res res;
		
		public ThreadA(Res res) {
			this.res = res;
		}
		@Override
		public void run() {
			int count = 0;
			while(count < 3){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					
				}
				
				synchronized (res) {
					if(res.flag != 0){
						try {
							res.wait();
						} catch (InterruptedException e) {
							
						}
					}else{
						System.out.println("A");
						res.flag = 1;
						++count;
					}
					
					res.notify();
				}
			}
		}
	}
	
	class ThreadB extends Thread{
		private Res res;
		
		public ThreadB(Res res) {
			this.res = res;
		}
		@Override
		public void run() {
			int count = 0;
			while(count < 3){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					
				}
				
				synchronized (res) {
					if(res.flag != 1){
						try {
							res.wait();
						} catch (InterruptedException e) {
							
						}
					}else{
						System.out.println("B");
						res.flag = 2;
						++count;
					}
					
					res.notify();
				}
			}
		}
	}
	
	class ThreadC extends Thread{
		private Res res;
		
		public ThreadC(Res res) {
			this.res = res;
		}
		@Override
		public void run() {
			int count = 0;
			while(count < 3){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					
				}
				
				synchronized (res) {
					if(res.flag != 2){
						try {
							res.wait();
						} catch (InterruptedException e) {
							
						}
					}else {
						System.out.println("C");
						res.flag = 0;
						++count;
					}
					
					res.notify();
				}
			}
		}
	}
}

        我在doMain方法中創建了3個線程,分別是ThreadA,ThreadB,ThreadC,它們分別打印A,B,C;然後使用線程的wait(),notify()實現線程間的通信。你們只需將代碼拷貝,運行一下就可以了。其中的知識還得你們自己悟。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章