如何保证多线程的顺序执行

版权声明:未经允许不得转载! https://blog.csdn.net/bingxuesiyang/article/details/88700221

多线程情况下由于会有CPU在不同线程之间的来回切换,各个线程的执行结果会产生交叉 。

举个例子:现有T1、T2、T3、主线程四个线程,如何安照T1执行完才执行T2、T2执行完才执行T3、T3执行完最后执行主线程才结束?

答案:使用join()方法,让其他线程等待。使用join的线程会独占执行资源,直到使用完毕,其它线程才能获取执行权。

代码示例如下:  

public class JoinDemo {

	public static void main(String[] args) throws InterruptedException {
		// 线程t1
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 5; i++) {
				    System.out.println("-----T1-----" + i);
				}
			}
		},"t1");
		t1.start();
		// 使用join让其他线程等待,本线程执行完成后其它线程才能执行
		t1.join();

		// 线程t2
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 5; i++) {
				    System.out.println("-----T2-----" + i);
				}
			}
		},"t2");
		t2.start();
		// 使用join让其他线程等待,本线程执行完成后其它线程才能执行
		t2.join();

		// 线程t3
		Thread t3 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 5; i++) {
				    System.out.println("-----T3-----" + i);
				}
			}
		},"t3");
		t3.start();
		// 使用join让其他线程等待,本线程执行完成后其它线程才能执行
		t3.join();

		System.out.println("-----main------");

	}

}

执行结果截图:

当然join()方法,也可以设置一个时间参数。

例如:
 

Thread t1 = new Thread();

t1 .start(); 

t1 .join(100) ;

Thread t2 = new Thread();

t2.start();

表示经过100ms后,不管t1有没有执行完毕,t2都会获得执行权。

猜你喜欢

转载自blog.csdn.net/bingxuesiyang/article/details/88700221