通过SynchronousQueue方式实现线程间数据传递

通过SynchronousQueue方式实现线程间数据传递

线程 A 与线程 B 共同持有一个 SynchronousQueue 的引用,线程 B 调用 take 方法,阻塞以等待; 线程 A 运行

后计算出结果,将结果 put 到 queue 中。

package com.example.synchronousqueuedemo;

import java.util.concurrent.SynchronousQueue;

/**
 * @author tom
 */
public class SynchronousQueueTest {

    public static void main(String[] args) {
        SynchronousQueue<Integer> queue = new SynchronousQueue<Integer>();
        // 线程A putThread
        Thread putThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("put thread start");
                try {
                    Thread.sleep(3000);
                    System.out.println("put thread put对象");
                    queue.put(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("put thread end");
            }
        });
        //线程B takeThread
        Thread takeThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("take thread start");
                try {
                    System.out.println("take thread 等待put对象");
                    System.out.println("take from putThread: " + queue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("take thread end");
            }
        });
        putThread.start();
        takeThread.start();
    }
}
# 程序输出
take thread start
take thread 等待put对象
put thread start
put thread put对象
put thread end
take from putThread: 1
take thread end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值