62,628
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) {
String zhongjiang = "99";
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);
Thread producer = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
String s =new Random().nextInt(100)+"";
queue.put(s);
System.out.println(Thread.currentThread().getName()+":"+s);
if (s.equalsIgnoreCase(zhongjiang)){
System.out.println(String.format("中奖号码[%s]已出,%s停止",zhongjiang,Thread.currentThread().getName()));
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
producer.setName("生产者线程");
producer.start();
for (int i = 0; i < 4; i++){
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
String s = queue.take();
System.out.println(Thread.currentThread().getName()+":"+s);
if (s.equalsIgnoreCase(zhongjiang)){
System.out.println(String.format("%s已中奖,中奖号码[%s]",Thread.currentThread().getName(),zhongjiang));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
consumer.setName("消费者线程"+i);
consumer.start();
}
}
生产者线程:91
消费者线程0:91
生产者线程:30
消费者线程1:30
生产者线程:65
消费者线程2:65
生产者线程:30
消费者线程3:30
生产者线程:77
消费者线程0:77
生产者线程:73
消费者线程1:73
生产者线程:18
消费者线程2:18
生产者线程:92
消费者线程3:92
生产者线程:42
消费者线程0:42
生产者线程:47
消费者线程1:47
生产者线程:1
消费者线程2:1
生产者线程:43
消费者线程3:43
生产者线程:19
消费者线程0:19
生产者线程:40
消费者线程1:40
生产者线程:96
消费者线程2:96
生产者线程:56
消费者线程3:56
生产者线程:38
消费者线程0:38
生产者线程:38
消费者线程1:38
生产者线程:48
消费者线程2:48
生产者线程:75
消费者线程3:75
生产者线程:27
消费者线程0:27
生产者线程:0
消费者线程1:0
生产者线程:35
消费者线程2:35
生产者线程:71
消费者线程3:71
生产者线程:6
消费者线程0:6
生产者线程:47
消费者线程1:47
生产者线程:54
消费者线程2:54
生产者线程:13
消费者线程3:13
生产者线程:74
消费者线程0:74
生产者线程:65
消费者线程1:65
生产者线程:49
消费者线程2:49
生产者线程:99
消费者线程3:99
中奖号码[99]已出,生产者线程停止
消费者线程3已中奖,中奖号码[99]
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);
Thread producer = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
String s =new Random().nextInt(100)+"";
queue.put(s);
System.out.println(Thread.currentThread().getName()+":"+s);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
producer.setName("生产者线程");
producer.start();
for (int i = 0; i < 4; i++){
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
String s = queue.take();
System.out.println(Thread.currentThread().getName()+":"+s);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
consumer.setName("消费者线程"+i);
consumer.start();
}
}



