多线程 16 java5阻塞队列的应用
(1)有两个线程,取数据,有一个线程写数据。
/**
* 有两个线程,取数据,有一个线程写数据。
*/
public class BlockingQueueTest {
public static void main(String[] args){
ExecutorService threadPool = Executors.newCachedThreadPool();
final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
for (int i=0;i<2;i++){
threadPool.execute(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println("线程"+Thread.currentThread().getName()+"往里面放入数据!");
queue.put(1);
System.out.println("队里有数据"+queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
while(true) {
try {
Thread.sleep(1000);
System.out.println("线程"+Thread.currentThread().getName()+"读取数据");
Integer data = queue.take();
System.out.println("线程读取到数据"+data);
System.out.println("队里有数据"+queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
(2)用阻塞队列实现同步通知的功能
public class BlockingQueueCommunication {
public static void main(String[] args) {
final Bussiness bussiness = new Bussiness();
new Thread(
new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 50; i++) {
bussiness.sub(i);
}
}
}
).start();
for (int i = 0; i <= 50; i++) {
bussiness.main(i);
}
}
static class Bussiness {
private static final ArrayBlockingQueue<Integer> queue1 = new ArrayBlockingQueue<>(1);//主
private static final ArrayBlockingQueue<Integer> queue2 = new ArrayBlockingQueue<>(1);//子
{
try {
System.out.println("xx");
queue2.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void main(int i) {
try {
queue2.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100; j++) {
System.out.println("main thread sequence of " + j + " of loop " + i);
}
try {
queue1.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sub(int i) {
try {
queue1.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10; j++) {
System.out.println("sub thread sequence of " + j + " of loop " + i);
}
try {
queue2.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
如有疑问,请发邮件:[email protected]
github:??https://github.com/wangrui0/