package pub.qingyun.weixin;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test1 {
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
private static CountDownLatch cdl = new CountDownLatch(100);
private static final Random random = new Random();
public void test() {
for (int i = 0; i < 100; i++) {
executorService.execute(new ThreadTest());
}
}
public static void main(String[] args) {
new Test1().test();
try {
cdl.await();
} catch (InterruptedException e) {
}
System.out.println("它们已经插完啦..............................");
executorService.shutdown();
}
class ThreadTest implements Runnable {
public void run() {
int time = random.nextInt(10000);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + "执行完了,耗时:" + time / 1000 + "秒");
cdl.countDown();
System.out.println("Count:" + cdl.getCount());
}
}
}
package pub.qingyun.weixin;
import java.util.Vector;
public class ThreadSubMain2 {
public static void main(String[] args) {
Vector<Thread> threads = new Vector<Thread>();
for (int i = 0; i < 10; i++) {
Thread iThread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("子线程" + Thread.currentThread() + "执行完毕");
});
threads.add(iThread);
iThread.start();
}
for (Thread iThread : threads) {
try {
iThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("主线执行。");
}
}
package pub.qingyun.weixin;
import java.util.concurrent.*;
public class CompletionServiceTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(5);
CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);
for (int i = 0; i < 20; i++) {
completionService.submit(new ReturnAfterSleepCallable(i));
}
System.out.println("after submit");
for (int i = 0; i < 20; i++) {
System.out.println("result: " + completionService.take().get());
}
System.out.println("after get");
executorService.shutdown();
}
}
class ReturnAfterSleepCallable implements Callable<String> {
int sleep;
public ReturnAfterSleepCallable(int sleep) {
this.sleep = sleep;
}
@Override
public String call() throws Exception {
System.out.println("-----------------------------");
TimeUnit.SECONDS.sleep(1);
return System.currentTimeMillis() + ",sleep=" + String.valueOf(sleep);
}
}