用sleep让主线程睡眠一段时间
package com.test;
public class test3 {
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("子线程执行");
}
}).start();
Thread.sleep(5000);
System.err.println("主线程执行");
}
}
JAVA主线程等待子线程 join
package com.test;
import java.util.Vector;
public class test {
static int count=0;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Vector ts=new Vector<>();
for (int i = 0; i < 100; i++) {
Run r=new Run();
Thread t=new Thread(r);
ts.add(t);
t.start();
}
for(Thread t:ts) {
t.join();
}
//Thread.sleep(4000);
System.err.println(count);
}
}
class Run implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
test.count++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
使用countDownLatch进行
package com.test;
import java.util.concurrent.CountDownLatch;
public class test4 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
final CountDownLatch cdl=new CountDownLatch(5);
for(int i=0;i<5;i++) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("子线程执行");
cdl.countDown();
}
}).start();
}
cdl.await();
System.err.println("主线程执行");
}
}
同步屏障CyclicBarrier
package com.test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class test5 {
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
final CyclicBarrier cyb=new CyclicBarrier(5);
for(int i=0;i<5;i++) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("子线程执行");
try {
cyb.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
cyb.await();
System.err.println("主线程执行");
}
}
Future的get()方法
package test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class FutureCook {
public static void main(String[] args) throws InterruptedException, ExecutionException {
long startTime = System.currentTimeMillis();
// 第一步 网购厨具
Callable onlineShopping = new Callable() {
@Override
public Chuju call() throws Exception {
System.out.println("第一步:下单");
System.out.println("第一步:等待送货");
Thread.sleep(5000); // 模拟送货时间
System.out.println("第一步:快递送到");
return new Chuju();
}
};
FutureTask task = new FutureTask(onlineShopping);
new Thread(task).start();
// 第二步 去超市购买食材
Thread.sleep(2000); // 模拟购买食材时间
Shicai shicai = new Shicai();
System.out.println("第二步:食材到位");
// 第三步 用厨具烹饪食材
if (!task.isDone()) { // 联系快递员,询问是否到货
System.out.println("第三步:厨具还没到,心情好就等着(心情不好就调用cancel方法取消订单)");
}
Chuju chuju = task.get();
System.out.println("第三步:厨具到位,开始展现厨艺");
cook(chuju, shicai);
System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
}
// 用厨具烹饪食材
static void cook(Chuju chuju, Shicai shicai) {}
// 厨具类
static class Chuju {}
// 食材类
static class Shicai {}
}
使用ExecutorService
import java.util.concurrent.*;
public class CommonThreadPool {
private static ExecutorService exec = new ThreadPoolExecutor(50, 100, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue(10000),
new ThreadPoolExecutor.CallerRunsPolicy());
public static void execute(Runnable command) {
exec.execute(command);
}
// 子线程执行结束future.get()返回null,若没有执行完毕,主线程将会阻塞等待
public static Future submit(Runnable command) { return exec.submit(command); }
// 子线程中的返回值可以从返回的future中获取:future.get();
public static Future submit(Callable command) {
return exec.submit(command);
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class ThreadTest {
@Test
public void ThreadTest() {
List futureList = new ArrayList<>();
for(int i = 0; i < 4; i++) {
int finalI = i;
Future future = CommonThreadPool.submit(() -> {
try {
System.out.println(finalI + " 我执行了。。。");
Thread.sleep(5000L);
System.out.println(finalI + " 我执行完了。。。");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
futureList.add(future);
}
//主线程处理其他工作,让子线程异步去执行.
mainThreadOtherWork();
System.out.println("now waiting sub thread done.");
//主线程其他工作完毕,等待子线程的结束, 调用future.get()系列的方法即可。
//
try {
for (Future future : futureList) {
System.out.println(future.get());
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
try {
System.out.println("处理一.");
Thread.sleep(1000);
System.out.println("处理二.");
Thread.sleep(1000);
System.out.println("处理三.");
Thread.sleep(1000);
System.out.println("处理四.");
Thread.sleep(1000);
System.out.println("所有处理完成.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void mainThreadOtherWork() {
System.out.println("主线程开始工作");
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程干完了");
}
}