java线程数据 交换_Java并发:线程间数据传递和交换

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

线程A与线程B共同持有一个SynchronousQueue的引用,线程B调用take方法,阻塞以等待; 线程A运行后计算出结果,将结果put到queue中;

48304ba5e6f9fe08f3fa1abda7d326ab.png

public class SynchronousQueueTest {

public static void main(String[] args) throws InterruptedException {

SynchronousQueue queue = new SynchronousQueue();

//线程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) {

}

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) {

}

System.out.println("take thread end");

}

});

putThread.start();

takeThread.start();

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

二、线程Exchanger工具类实现线程间的数据交换:

当一个线程到达exchange调用点时,如果它的伙伴线程此前已经调用了此方法,那么它的伙伴会被调度唤醒并与之进行对象交换,然后各自返回。如果它的伙伴还没到达交换点,那么当前线程将会被挂起,直至伙伴线程到达——完成交换正常返回;或者当前线程被中断——抛出中断异常;又或者是等候超时——抛出超时异常。

48304ba5e6f9fe08f3fa1abda7d326ab.png

public class ExchangerTest {

public static void main(String[] args) {

ExecutorService service = Executors.newCachedThreadPool();

final Exchanger exchanger = new Exchanger();

service.execute(new Runnable(){

public void run() {

try {

String data1 = "thread-1-data";

System.out.println("线程" + Thread.currentThread().getName() +"正在把数据" + data1 +"换出去");

Thread.sleep((long)(Math.random()*10000));

String data2 = (String)exchanger.exchange(data1);

System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2);

}catch(Exception e){

}

}

});

service.execute(new Runnable(){

public void run() {

try {

String data1 = "thread-2-data";

System.out.println("线程" + Thread.currentThread().getName() + "正在把数据" + data1 +"换出去");

Thread.sleep((long)(Math.random()*10000));

String data2 = (String)exchanger.exchange(data1);

System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2);

}catch(Exception e){

}

}

});

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值