可以利用阻塞队列实现同步通知的功能。假如有A、B两个线程,共同执行一个任务,彼此通知、交替执行该任务。如图:
通过代码看一下执行的效果:
- 1-1 一个阻塞队列实现同步通知的例子。
- import java.util.Collections;
- import java.util.concurrent.ArrayBlockingQueue;
- import java.util.concurrent.BlockingQueue;
- import java.util.concurrent.atomic.AtomicInteger;
- /*
- * 子线程循环10次,接着主线程循环100次,接着有回到子线程循环10次,
- * 接着再回到主线程循环100次,如此循环50次,请写出程序。
- * 用两个具有1个空间的队列来实现同步通知单的功能
- */
- public class BlockQueueConmunication1 {
- public static void main(String[] args) {
- final Business business=new Business();
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- for(int i=1;i<=50;i++){
- business.sub(i);
- }
- }
- }
- ).start();
- for(int i=1;i<=50;i++){
- business.main(i);
- }
- }
- static class Business{
- BlockingQueue<Integer> queue1=new ArrayBlockingQueue<Integer>(1);//2个队列
- BlockingQueue<Integer> queue2=new ArrayBlockingQueue<Integer>(1);
- //匿名构造方法,创建几个对象调用几次,而static只调用一次
- { //构造方法先给他=赋值,让queue2先不要执行
- //Collections.synchronizedMap(null);//并发的集合,在这只是在练习的熟悉,与本程序没有关系
- try {
- queue2.put(1);
- //System.out.println("sahdghsagdhasdgh");//测试语句,检查知否执行到此处
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public void sub(int i){
- try {
- queue1.put(1);
- //System.out.println("sahdghsagdhasdgh");
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- for (int j = 1; j <= 10; j++) {
- System.out.println("sub thread sequece of "+j+",loop of"+i);
- }
- try {
- queue2.take();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public void main(int i){
- try {
- queue2.put(1);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }//刚开始的时候是满的,上面已经给他赋值了
- for (int j = 1; j <= 100; j++) {
- System.out.println("main thread sequece of "+j+",loop of"+i);
- }
- try {
- queue1.take();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
上述代码实是在 一个线程通信的例子 的基础上修改的,感兴趣的朋友可以看一下。 两段代码实现了相同的功能。