举例
/**
* 多线程Test
*/
public class Main {
static Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread01");
}
});
static Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread02");
}
});
static Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread03");
}
});
static Thread thread4 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread04");
}
});
static Thread thread5 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread05");
}
});
public static void main(String[] args) {
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
输出结果,顺序并不是固定的,而是随机在改变的
1、join方式
原理就是让main这个主线程等待子线程结束,然后主线程再执行接下来的其他线程任务
public static void main(String[] args) throws Exception {
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
thread4.start();
thread4.join();
thread5.start();
thread5.join();
}
2、ExecutorService方式
原理其实就是将线程用排队的方式扔进一个线程池里,让所有的任务以单线程的模式,按照FIFO先进先出、LIFO后进先出、优先级等特定顺序执行,但是这种方式也是存在缺点的,就是当一个线程被阻塞时,其它的线程都会受到影响被阻塞,不过依然都会按照自身调度来执行,只是会存在阻塞延迟。
static ExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
public static void main(String[] args) throws Exception {
executorService.submit(thread1);
executorService.submit(thread2);
executorService.submit(thread3);
executorService.submit(thread4);
executorService.submit(thread5);
executorService.shutdown();
}