join()方法:当前线程需等待指定的线程结束后才能继续运行。该方法需要抛异常。
Example:
场景,老板约四个人打麻将。其中,老板是主线程,四个玩家是分线程。并且,要等待四个人全部到齐后才能开局。
代码:ThreadDemo2
Daomon:守护线程
Thread.setDaemon(true);将线程设置为守护线程,对其他非守护线程提供服务。若进程中剩余的线程都是守护线程,则进程终止。
Example:
public class ThreadDemo1 {
public static void main(String[] args){
Player p1=new Player("1号",1000);
Player p2=new Player("2号",2000);
Player p3=new Player("3号",3000);
Player p4=new Player("4号",4000);
p1.start();
p2.start();
p3.start();
p4.start();
try{
p1.join();
p2.join();
p3.join();
p4.join();
}
catch(Exception e){
}
System.out.println("人到齐了,可以开始了");//因为前面有join()方法,所以该句只能等到前面所有线程结束之后才能运行
}
}
class Player extends Thread{
private String name;
private int time;
public Player(String name,int time){
this.name=name;
this.time=time;
}
public void run(){
System.out.println(name+"出发了!");
try{
Thread.sleep(time);
}
catch(Exception e){
}
System.out.println(name+"到了!耗时:"+time);
}
}
public class ThreadDemo2 {
public static void main(String[] args){
Box num1=new Box("num-1",6000);
Box num2=new Box("num-2",5000);
Waiter w=new Waiter();
w.setDaemon(true);//将服务员线程设置为守护线程,如果不将服务员设为守护线程,那么报时操作将一直进行下去。
num1.start();
num2.start();
w.start();
}
}
class Box extends Thread{
private String num;
private int time;
public Box(String num,int time ){
this.num=num;
this.time=time;
}
public void run(){
System.out.println(num+"包厢开始消费");
try{
Thread.sleep(time);
}
catch(Exception e){
}
System.out.println(num+"结束消费,消费时间为:"+time);
}
}
class Waiter extends Thread{
public void run(){
while(true){ //死循环,直到其他线程执行结束才结束
//打印当前系统时间
System.out.println(new java.util.Date());
try{
Thread.sleep(1000);//每隔一秒打印一次
}
catch(Exception e){
}
}
}
}