功能,实现多个线程同时打印数据
1 package test;
2
3
4 import java.util.concurrent.ArrayBlockingQueue;
5 import java.util.concurrent.BlockingDeque;
6 import java.util.concurrent.BlockingQueue;
7
8 /**
9 * 多线程队列操作
10 */
11 public class threadQueue {
12 public static void main(String[] args) throws InterruptedException {
13 //将阻塞队列初始化为要处理的数据大小,初始化为1也行,但顺序会乱
14 final BlockingQueue<String> que=new ArrayBlockingQueue<>(20);
15 for(int i=0;i<4;i++){
16 new Thread(new Runnable() {
17 @Override
18 public void run() {
19 String take = null;
20 //这里没有while的话每个线程打印一次就结束了,也就是只能打印四个结果值
21 while (true) {
22 try {
23 take = que.take();
24 put1(take);
25 } catch (InterruptedException e) {
26 e.printStackTrace();
27 }
28 }
29
30 }
31 }
32
33 ).start();
34 }
35 for(int i=1;i<=20;i++){
36 // put1(i + "\tww");
37 final String t=i + "\tww";
38 //将数据添加到队列中
39 que.put(t);
40
41 };
42
43 }
44
45 public static void put1(String s){
46 System.out.println(s);
47 try {
48 Thread.sleep(4000);
49 } catch (InterruptedException e) {
50 e.printStackTrace();
51 }
52
53 }
54
55
56 }