代码1:
package com.zkk;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
public class Test4 {
public static void main(String[] args) {
final SynchronousQueue<String> syn = new SynchronousQueue<String>();
ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 3; i++) {
Runnable runn = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(new Random().nextInt(1000));
syn.put("a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
threadPool.execute(runn);
}
}
}
以上的代码不会打印任何东西。
文档原话:其中每个插入操作必须等待另一个线程的对应移除操作
package com.zkk;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
public class Test4 {
public static void main(String[] args) {
final SynchronousQueue<String> syn = new SynchronousQueue<String>();
ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 3; i++) {
final int task=i;
Runnable runn = new Runnable() {
@Override
public void run() {
try {
System.out.println("aa");
Thread.sleep(new Random().nextInt(1000));
syn.put("a"+task);
System.out.println("bb");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
threadPool.execute(runn);
}
try {
String take1 = syn.take();
System.out.println("take1:"+take1);
String take2 = syn.take();
System.out.println("take2:"+take2);
String take3 = syn.take();
System.out.println("take3"+take3);
String take4 = syn.take();
System.out.println("take4:"+take4);
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码打印结果:
aa
aa
aa
take1:a0
bb
bb
take2:a2
bb
take3a1
充分说明了这一点
而BlockingQueue 这没有文档这点