方法一:在子线程中通过join()方法指定顺序
通过join()方法使当前线程“阻塞”,等待指定线程执行完毕后继续执行,比如在线程thread2中,加上一句thread1.join(),其意义在于,当前线程2运行到此行代码时会进入阻塞状态,直到线程thread1执行完毕后,线程thread2才会继续运行,这就保证了线程thread1与线程thread2的运行顺序
方法二:在主线程中通过join()方法指定顺序
上面我们是在子线程中指定join()方法,我们还可以在主线程中通过join()方法让主线程阻塞等待以达到指定顺序执行的目的
方法三:使用Object的wait和notifyAll方法
package printABC.method1;//第一种方法,使用Object的wait和notifyAll方法public class TestPrint {static int count = 0;static final Object obj = new Object();Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {while (true) {synchronized (obj) {if (count % 3 == 0) {System.out.println("A");count++;obj.notifyAll();} elsetry {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}});Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {while (true) {synchronized (obj) {if (count % 3 == 1) {System.out.println("B");count++;obj.notifyAll();} elsetry {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}});Thread t3 = new Thread(new Runnable() {@Overridepublic void run() {while (true) {synchronized (obj) {if (count % 3 == 2) {System.out.println("C");count++;obj.notifyAll();} elsetry {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}});public void fun() {t3.start();t1.start();t2.start();}public static void main(String[] args) {TestPrint tp = new TestPrint();long t1 = System.currentTimeMillis();tp.fun();while (true) {if (System.currentTimeMillis() - t1 >= 10)// 运行10个毫秒System.exit(0);}}}
一种方式可以通过求余方法来判断到哪个线程执行,当执行完该线程之后,再使用notifyAll()方法来唤醒线程,让后面的线程继续执行
如果觉得《如何让多线程按顺序执行》对你有帮助,请点赞、收藏,并留下你的观点哦!