练习题:
编程实现:线程A向队列Q中不停写入数据,线程B从队列Q中不停读取数据(只要Q中有数据)。
结果演示:
3458722 : 351288361
-----
3458723 : 144892109
-----
3458724 : 1187712821
-----
3458725 : 1027621134
-----
3458726 : 1659210189
-----
3458727 : 1418092690
-----
3458728 : 371476613
-----
3458729 : 33977233
-----
3458730 : 1428925512
-----
3458737 : 263381771
-----
3458738 : 66602656
-----
3458739 : 1806626536
-----
3458740 : 403997302
-----
3458741 : 1652835900
-----
3458742 : 500911881
-----
//...
//基本等于死循环
<<< 请您给予关注增加动力 >>>
解题代码:
import java.util.ArrayDeque;
import java.util.Random;
public class Demo {
public static void main(String[] args) {
Random random = new Random(100);
ArrayDeque<Integer> q = new ArrayDeque<>();
String str = "abc";
new Thread("A") {
@Override
public void run() {
while (true) {
synchronized (str) {
str.notifyAll();
q.push(Math.abs(random.nextInt()));
System.out.println("-----");
if (q.size() > 0) {
try {
str.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}.start();
Thread t = new Thread("B") {
int count = 0;
@Override
public void run() {
while (true) {
synchronized (str) {
str.notifyAll();
if (q.size() == 0) {
try {
str.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer i = q.poll();
count++;
System.out.println(count + " : " + i);
}
}
}
};
t.start();
try {
t.join();
} catch (
InterruptedException e) {
e.printStackTrace();
}
}
}