Problem Description:
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "...." + i);
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "...." + i);
}
}
});
thread1.start();
thread2.start();
The result: there is no visible multiple threads running order
Thread-1....0
Thread-1....1
Thread-1....2
Thread-2....0
Thread-1....3
Thread-1....4
Thread-1....5
Thread-1....6
Method 1: join
Explanation: wait method join Object class source code execution. The principle is the main thread in wait, you know the child thread execution to continue until the end of the main thread.
thread1.start();
thread1.join();
thread2.start();
thread2.join();
Method 2: using a single thread pool Executors.newSingleThreadExecutor ()
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(thread1);
executor.submit(thread2);
executor.submit(thread3);
executor.shutdown();