俩个线程之间交换数据之后继续运行,除了全局静态变量,jdk5提供了Exchanger类来解决这个问题。不多说,直接上例子
- package com.skydream.thread.exchanger;
- import java.util.concurrent.Exchanger;
- public class ExchangerTest {
- /**
- * @param args
- * @throws InterruptedException
- */
- public static void main(String[] args) throws InterruptedException {
- final Exchanger<String> objExchanger = new Exchanger<String>();
- new Thread(){
- public void run() {
- System.out.println("子线程正在运行");
- try {
- Thread.sleep(5000);
- String strData = objExchanger.exchange("skydream");
- System.out.println("交换后的数据"+strData);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- };
- }.start();
- System.out.println("子线程已经启动");
- String strChildThreadData = objExchanger.exchange("main data");
- System.out.println("主线程交换后的数据 "+strChildThreadData);
- }
- }