JAVA notifyAll wait 实例

两个线程,分别有两数据结构:1到10的数据和A到E的字符。要求打印出:12A34B56C78D910E 。程序如下:

 

public class NotifyAllTest {

	/** 期望的打印结果:12A34B56C78D910E ,怎么搞 ?
	 * @param args
	 */
	public static void main(String[] args) {
		int[] numArr = {1,2,3,4,5,6,7,8,9,10};
		char[] charArr = {'A','B','C','D','E'};
		NotifyAllTest obj = new NotifyAllTest();
		new Thread(new OneThread(numArr, obj)).start();
		new Thread(new TwoThread(charArr, obj)).start();
	}
}

class OneThread implements Runnable {

	private int[] numArr;

	private NotifyAllTest	notifyAllTest;
	
	public OneThread(int[] numArr,NotifyAllTest	notifyAllTest) {
		this.notifyAllTest = notifyAllTest;
		this.numArr = numArr;
	}
	
	@Override
	public void run() {
		synchronized (notifyAllTest) {
			for(int i = 0 ,len = numArr.length; i < len ; i++) {
				if(i%2==0){
					try {
						notifyAllTest.wait(200);
						notifyAllTest.notifyAll();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} 
				System.out.print(numArr[i]);
			}
		}
	}
}

class TwoThread implements Runnable {
	
	private char[] charArr;

	private NotifyAllTest	notifyAllTest;

	public TwoThread(char[] charArr,NotifyAllTest	notifyAllTest) {
		this.charArr = charArr;
		this.notifyAllTest = notifyAllTest;
	}
	
	@Override
	public void run() {
		synchronized (notifyAllTest) {
			for(int i = 0 ,len = charArr.length; i < len ; i++) {
				if(i%1==0){
					try {
						notifyAllTest.wait(300);
						notifyAllTest.notifyAll();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} 
				System.out.print(charArr[i]);
			}
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值