多线程并发练习

简单的生产者和消费者的多线程并发练习。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.gxnu.bigdata.study.concurrent;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.junit.Test;

public class {

public static void main(String[] args) {
BlockingQueue<Integer> bq = new ArrayBlockingQueue<>(10);
new Thread(()->{
Random random = new Random();
while(true){
int num = random.nextInt(101);
try {
bq.put(num);
Thread.sleep(100);
System.out.println("生产者:"+num);
} catch (Exception e) {
e.printStackTrace();
}
}}).start();

new Thread(()->{
while(true){
try {
int take = bq.take();
System.out.println("消费者:"+take);
} catch (Exception e) {
e.printStackTrace();
}
}}).start();
}
}

limaodeng

scribble