public class ThreadTest2 {
/**
* 执行顺序
* 如果不加join,线程的执行顺序是由CPU随机分配的。
* 当前线程调用join(),作用:是的当前线程调用run()完之后执行join()之后的方法*/
public static void main(String[] args) {
try {
Thread thread=new Thread(new RunnableTest("线程1"));
thread.start();
thread.join();
Thread thread2=new Thread(new RunnableTest("线程2"));
thread2.start();
thread2.join();
Thread thread3=new Thread(new RunnableTest("线程3"));
thread3.start();
thread3.join();
} catch (Exception e) {
}
}
public static class RunnableTest implements Runnable {
String name;
int i=0;
public RunnableTest(String name){
this.name=name;
}
private String getName(){
return name;
}
@Override
public void run() {
while (i<5) {
System.out.println( getName()+"----"+(++i));
}
}
}
}
/**
* 结果*/
/*线程1----1
线程1----2
线程1----3
线程1----4
线程1----5
线程2----1
线程2----2
线程2----3
线程2----4
线程2----5
线程3----1
线程3----2
线程3----3
线程3----4
线程3----5*/
三个线程保证线程1最先运行完,线程2次之运行完,线程3最后运行完
最新推荐文章于 2024-03-29 13:00:23 发布
