小言_互联网的博客

使用thread实现打印ABCABCABC

360人阅读  评论(0)

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()实现线程间的通信。你们只需将代码拷贝,运行一下就可以了。其中的知识还得你们自己悟。


转载:https://blog.csdn.net/chenmin_test/article/details/101636820
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场