多线程的执行顺序,在下进来了解了一点
先来原来的没有排序的线程是怎么样的
public class App {
static Thread thread1 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread1");
}
});
static Thread thread2 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread2");
}
});
static Thread thread3 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
//join:让主线程等待子线程结束以后才能继续运行
System.out.println("Hello World");
thread1.start();
thread2.start();
thread3.start();
}
}
结果是
然后第一种是join:
public class App {
static Thread thread1 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread1");
}
});
static Thread thread2 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread2");
}
});
static Thread thread3 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
//join:让主线程等待子线程结束以后才能继续运行
System.out.println("Hello World");
thread1.start();
thread1.join();
thread2.start();
thread1.join();
thread3.start();
}
}
然后结果
第二种是用了
ExecutorService executorService = Executors.newSingleThreadExecutor();
public class App {
static Thread thread1 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread1");
}
});
static Thread thread2 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread2");
}
});
static Thread thread3 =new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
//join:让主线程等待子线程结束以后才能继续运行
/* System.out.println("Hello World");
thread1.start();
thread1.join();
thread2.start();
thread1.join();
thread3.start();*/
executorService.submit(thread1);
executorService.submit(thread2);
executorService.submit(thread3);
executorService.shutdown();
}
}