Exchanger api详解
程序员文章站
2024-01-03 23:48:10
今天时间学习Exchangerapi,该类是JUC原子包中的类,通过单元测试代码把所有public api方法跑了一遍,大致了解了底层实现,初学乍练,有很多一知半解的地方,待后续有了深入理解再来补充package test.java.util.concurrent;import java.util.concurrent.Exchanger;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutExce....
今天时间学习Exchanger api,该类是JUC原子包中的类,通过单元测试代码把所有public api方法跑了一遍,大致了解了底层实现,初学乍练,有很多一知半解的地方,待后续有了深入理解再来补充
package test.java.util.concurrent;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
/**
* Exchanger的测试类
*
* @date 2020-07-14 22:54:19
*/
public class ExchangerTest {
/**
* 无参构造函数
* @Param
*/
@Test
public void testConstruct0()throws Exception{
System.out.println(Runtime.getRuntime().availableProcessors());
Exchanger testObj=new Exchanger();
System.out.println(testObj.toString());
}
class InnerExchangerTest extends Thread{
private Exchanger exchanger;
private String name;
private String ex;
InnerExchangerTest(Exchanger exchanger,String name,String ex){
this.exchanger=exchanger;
this.name=name;
this.ex=ex;
}
@Override
public void run() {
try {
System.out.println(name+":"+exchanger.exchange(ex,1L,TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
/**
* 两个线程之间交换参数
* @Param
*/
@Test
public void testExchange1()throws Exception{
Exchanger testObj=new Exchanger();
InnerExchangerTest test1=new InnerExchangerTest(testObj,"test1","1111");
InnerExchangerTest test2=new InnerExchangerTest(testObj,"test2","2222");
test1.start();
test2.start();
}
/**
*两个线程之间交换参数,在指定范围内
* @Param
*/
@Test
public void testExchange()throws Exception{
Exchanger testObj=new Exchanger();
InnerExchangerTest test1=new InnerExchangerTest(testObj,"test1","1111");
InnerExchangerTest test2=new InnerExchangerTest(testObj,"test2","2222");
test1.start();
test2.start();
}
}
本文地址:https://blog.csdn.net/u011106263/article/details/107350150