1 Star 0 Fork 45

pony1223/TestUI

forked from ldh123/TestUI 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ExchangeTest.java 2.49 KB
一键复制 编辑 原始数据 按行查看 历史
ldh123 提交于 2019-04-02 19:01 +08:00 . opt
package util;
import java.util.concurrent.Exchanger;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by ldh on 2019/4/1.
*/
public class ExchangeTest {
public static void main(String[] args) {
testExchanger();
}
public static void testExchanger() {
ExecutorService executor = Executors.newFixedThreadPool(2);
Exchanger<Integer> exchanger = new Exchanger();
executor.execute(()->{
for (int i=0; i<100; i+=2) {
try {
int r = exchanger.exchange(i);
System.out.println("thread1: " + i + ", r:" + r);
} catch (Exception e) {
e.printStackTrace();
}
}
});
executor.execute(()->{
for (int i=1; i<100; i+=2) {
try {
int r = exchanger.exchange(10);
// Thread.sleep(1);
System.out.println("thread2: " + i + ", r:" + r);
} catch (Exception e) {
e.printStackTrace();
}
}
});
executor.shutdown();
}
public void commonTest() {
ExecutorService executor = Executors.newFixedThreadPool(2);
ExchangeTest exchangeTest = new ExchangeTest();
executor.execute(()->{
for (int i=0; i<100; i+=2) {
try {
exchangeTest.println("thread1", i);
} catch (Exception e) {
e.printStackTrace();
}
}
});
executor.execute(()->{
for (int i=1; i<100; i+=2) {
try {
exchangeTest.println2("thread2", i);
} catch (Exception e) {
e.printStackTrace();
}
}
});
executor.shutdown();
}
private boolean printlnThread = true;
public synchronized void println(String threadName, int n) throws InterruptedException {
if (!printlnThread) {
wait();
}
System.out.println(threadName + ":" + n);
printlnThread = false;
notifyAll();
}
public synchronized void println2(String threadName, int n) throws InterruptedException {
if (printlnThread) {
wait();
}
System.out.println(threadName + ":" + n);
printlnThread = true;
notifyAll();
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/packagejava/TestUI.git
git@gitee.com:packagejava/TestUI.git
packagejava
TestUI
TestUI
master

搜索帮助