多线程之同步队列

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:52   2104   0
package com.lyon.juc;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

//同步队列
public class BlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> strings = new SynchronousQueue<>();
        new Thread(()->{
            try{
                System.out.println(Thread.currentThread().getName()+" put 1");
                strings.put("1");
                System.out.println(Thread.currentThread().getName()+" put 2");
                strings.put("2");
                System.out.println(Thread.currentThread().getName()+" put 3");
                strings.put("3");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();


        new Thread(()->{
            try{
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+" =>"+strings.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+" =>"+strings.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+" =>"+strings.take());

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();

    }
}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP