java中线程执行顺序控制

一:join()方法.

thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。

public class JoinTest2 {
 
     // 1.现在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行
 
     public static void main(String[] args) {
 
         final Thread t1 =  new Thread( new Runnable() {
 
             @Override
             public void run() {
                 System.out.println( "t1" );
             }
         });
         final Thread t2 =  new Thread( new Runnable() {
 
             @Override
             public void run() {
                 try {
                     // 引用t1线程,等待t1线程执行完
                     t1.join();
                 catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println( "t2" );
             }
         });
         Thread t3 =  new Thread( new Runnable() {
 
             @Override
             public void run() {
                 try {
                     // 引用t2线程,等待t2线程执行完
                     t2.join();
                 catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println( "t3" );
             }
         });
         t3.start(); //这里三个线程的启动顺序可以任意,大家可以试下!
         t2.start();
         t1.start();
     }
}
二:synchronized

public class TestSync implements Runnable {


	Timer timer = new Timer();
	public static void main(String[] args) {
		TestSync testSync = new TestSync();
		Thread t1 = new Thread(testSync);
		Thread t2 = new Thread(testSync);
		t1.setName("t1");
		t2.setName("t2");
		t1.start();
		t2.start();
	}
	
	public void run() {
		timer.add(Thread.currentThread().getName());
	}
}


class Timer {
	private static int num = 0;
	//public void add(String name) {
	public synchronized void add(String name) {//执行这个方法的过程中当前对象被锁定
		//synchronized (this) {//锁定当前对象
			num++;
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) { }
			System.out.println(name + "你是第" + num + "个使用Timer的线程");
		//}
	}
}


你可能感兴趣的:(java中线程执行顺序控制)