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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值