Java multithreading - scheduling (merging) of threads

The meaning of thread merging is to merge the threads of several parallel threads into a single thread for execution. The application scenario is that the join method can be used when a thread must wait for another thread to finish executing.

join is a non-static method, defined as follows:
void join(): Wait for the thread to terminate. 
void join(long millis): Wait for the thread to terminate for up to millis milliseconds. 
void join(long millis, int nanos): The maximum time to wait for this thread to terminate is millis milliseconds + nanos nanoseconds.

copy code
package cn.thread;

/**
 * Thread scheduling (merging)
 *
 * @author Lin Jiqin
 * @version 1.0 2013-7-24 上午09:49:47
 */
public class ThreadJoin {
    public static void main(String[] args) {
        ThreadJoin join = new ThreadJoin();
        Thread t1 = join.new MyThread1();
        t1.start();

        for (int i = 0; i < 20; i++) {
            System.out.println( "Main thread's first" + i + "execution!" );
             if (i > 2 )
                 try {
                     // t1 thread is merged into the main thread, the main thread stops the execution process and executes the t1 thread instead , continue until t1 is executed. 
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
        }
    }

    class MyThread1 extends Thread {
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println( "Thread 1" + i + "execution!" );
            }
        }
    }
}
copy code
copy code
The 0th execution of the main thread!
The first execution of the main thread!
The second execution of the main thread!
The third execution of the main thread!
Thread 1 executes for the 0th time!
Thread 1 executes for the first time!
Thread 1 executes for the second time!
Thread 1 executes for the 3rd time!
Thread 1 executes for the 4th time!
Thread 1 executes for the 5th time!
Thread 1 executes for the 6th time!
Thread 1 executes for the 7th time!
Thread 1 executes for the 8th time!
Thread 1 executes for the 9th time!
The fourth execution of the main thread!
The 5th execution of the main thread!
The 6th execution of the main thread!
The 7th execution of the main thread!
The 8th execution of the main thread!
The ninth execution of the main thread!
The 10th execution of the main thread!
The 11th execution of the main thread!
The 12th execution of the main thread!
The 13th execution of the main thread!
The 14th execution of the main thread!
The 15th execution of the main thread!
The 16th execution of the main thread!
The 17th execution of the main thread!
The 18th execution of the main thread!
The 19th execution of the main thread!
copy code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326267202&siteId=291194637