有三个线程,怎么让他们按顺序执行
Thread类构造方法:1.Thread();2.Thread(String name);3.Thread(Runable r);4.Thread(Runable r, String name);
thread类常用方法:start();//启动线程getId();//获得线程IDgetName();//获得线程名字getPriority();//获得优先权isAlive();//判断线程是否活动isDaemon();//判断是否守护线程getState();//获得线程状态sleep(long mill);//休眠线程join();//等待线程结束yield();//放弃cpu使用权利interrupt();//中断线程currentThread();//获得正在执行的线程对象
下面实例用join()实现线程按顺序执行:
/*有三个线程T1 T2 T3,如何保证他们按顺序执行-转载在T2的run中,调用t1.join,让t1执行完成后再让T2执行在T2的run中,调用t2.join,让t2执行完成后再让T3执行*/public class ThreadByOrder { static Thread t1 = new Thread(new Runnable() {@Override public void run() {System.out.println("t1");}}); static Thread t2 = new Thread(new Runnable() {@Override public void run() { try {t1.join();Thread.sleep(500);} catch (InterruptedException e) { // TODO Auto-generated catch blocke.printStackTrace();}System.out.println("t2");}}); static Thread t3 = new Thread(new Runnable() {@Override public void run() { try {t2.join();Thread.sleep(500);} catch (InterruptedException e) { // TODO Auto-generated catch blocke.printStackTrace();}System.out.println("t3");}}); public static void main(String[] args) {t1.start();t2.start();t3.start();}}
执行结果: