import cn.hutool.core.lang.Console;
|
import cn.hutool.core.thread.ThreadUtil;
|
import cn.hutool.core.util.NumberUtil;
|
import org.junit.Test;
|
|
import java.util.concurrent.*;
|
|
public class ThreadTest {
|
|
@Test
|
public void test1() throws InterruptedException, ExecutionException, TimeoutException {
|
|
CompletionService<Object> objectCompletionService = ThreadUtil.newCompletionService();
|
|
CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(4);
|
|
objectCompletionService.submit(new Callable<Object>() {
|
|
@Override
|
public Object call() throws Exception {
|
System.out.println("第一个任务");
|
try {
|
return 1;
|
} finally {
|
countDownLatch.countDown();
|
}
|
}
|
});
|
|
objectCompletionService.submit(new Callable<Object>() {
|
|
@Override
|
public Object call() throws Exception {
|
System.out.println("第二个任务");
|
// ThreadUtil.sleep(3000);
|
try {
|
return 2;
|
} finally {
|
countDownLatch.countDown();
|
}
|
}
|
});
|
|
objectCompletionService.submit(new Callable<Object>() {
|
|
@Override
|
public Object call() throws Exception {
|
System.out.println("第三个任务");
|
try {
|
return 3;
|
} finally {
|
countDownLatch.countDown();
|
}
|
}
|
});
|
|
objectCompletionService.submit(new Callable<Object>() {
|
|
@Override
|
public Object call() throws Exception {
|
// int a=5/0;
|
// ThreadUtil.sleep(11000);
|
// ThreadUtil.sleep(3000);
|
System.out.println("第四个任务");
|
try {
|
return 4;
|
} finally {
|
countDownLatch.countDown();
|
}
|
}
|
});
|
|
long count = countDownLatch.getCount();
|
Console.log("latch:{}",count);
|
|
countDownLatch.await();
|
|
for (int i = 0; i < 4; i++) {
|
Object o= objectCompletionService.take().get();
|
System.out.println(o);
|
}
|
|
ThreadLocal<Object> threadLocal = ThreadUtil.createThreadLocal(false);
|
|
threadLocal.set("123");
|
|
Object o = threadLocal.get();
|
|
System.out.println(o);
|
|
|
}
|
|
class A implements Runnable{
|
|
@Override
|
public void run() {
|
System.out.println("开始");
|
}
|
}
|
}
|