Thread 和 Executors.newSingleThreadExxcutor 对比分析
/*
主线程与子线程并行运行
*/
package test;
public class ReviewThread
{
public static void main(String[] args)
{
ChildrenThread childrenThread=new ChildrenThread();
childrenThread.start();
System.out.println("主线程也在运行");
}
}
class ChildrenThread extends Thread
{
public ChildrenThread()
{
super();
}
@Override
public void run()
{
System.out.println("这是一个线程");
}
}
主线程也在运行
这是一个线程
package test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ReoperatorCountDownLatch
{
public static void main(String[] args)
{
CountDownLatch countDownLatch=new CountDownLatch(2);
//System.out.println("主线程开始执行.............");
//第一个子线程执行
ExecutorService es1=Executors.newSingleThreadExecutor();
es1.execute(()->
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("这是第一个子线程");
countDownLatch.countDown();
});
es1.shutdown();
ExecutorService es2=Executors.newSingleThreadExecutor();
es2.execute(()->
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("这是第二个子线程");
countDownLatch.countDown();//控制当前线程的数量
});
es2.shutdown();
try
{
countDownLatch.await();//哪个线程执行,就是哪个线程等待
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("主线程继续执行");
}
}