java notifyall wait,JAVA notifyAll wait 范例

该博客主要探讨了如何使用Java多线程实现两个数据结构间的交替打印。程序创建了两个线程,一个处理1到10的整数,另一个处理'A'到'E'的字符。通过`synchronized`关键字和`wait()`、`notifyAll()`方法协调线程间的同步,以达到预期的打印顺序12A34B56C78D910E。
摘要由CSDN通过智能技术生成

两个线程,分别有两数据结构: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 NotifyAllTestnotifyAllTest;

public OneThread(int[] numArr,NotifyAllTestnotifyAllTest) {

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 NotifyAllTestnotifyAllTest;

public TwoThread(char[] charArr,NotifyAllTestnotifyAllTest) {

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]);

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值