java09-05 join_daemon

yield:放弃CPU的抢占全

jion:等制定的线程执行完毕后继续运行

sleep:静态方法 ,让线程休眠毫秒

daemon:守护线程,如果应用程序里面都是守护线程,则程序结束

class ThreadDemo2{
public static void main(String[] agrs) {

Player p1 =new Player("史泰龙",8000);
Player p2 =new Player("成龙",5000);
Player p3 =new Player("李小龙",2000);
Player p4 =new Player("李连杰",3000);
p1.start();
p2.start();
p3.start();
p4.start();

//join 等这个分线程执行完毕在往下执行 join方法也有异常
try{
p1.join();
p2.join();
p3.join();
p4.join();
}
catch(Exception e){

}

System.out.println("人到齐了");
}

}

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{
//让当前进程休眠time 毫秒
Thread.sleep(time);
}
catch(Exception e){
}
System.out.println("玩家" +name+"到了");

}
}

ktv点歌线程

------------------------------------------------------------------

class NineThreadDemo3{
public static void main(String[] agrs) {

Room R =new Room("1",8000);
Waiter w =new Waiter();
//一个主线程,一个房间线程,一个服务生线程
//设置线程为守护线程 w.setDaemon(true); 守护非守护线程的
//w.setDaemon(true);
R.start();
w.start();

}

}

class Room extends Thread{
private String no;
private int time;
public Room( String no,int time){
this.no =no;
this.time=time;
}


public void run(){
System.out.println("房间"+no+"正在唱歌");
try{
//让当前进程休眠 time 毫秒
Thread.sleep(time);
}
catch(Exception e){
}
System.out.println("房间" +no+"买单");

}
}


//服务员每隔一秒就包时间
class Waiter extends Thread{
//只有是服务员就是守护线程
public Waiter(){
this.setDaemon(true);
}
public void run(){
while(true){
System.out.println(new java.util.Date());
try{
//每隔一秒报一次
Thread.sleep(1000);
}
catch(Exception e){

}
}
}
}

猜你喜欢

转载自www.cnblogs.com/simly/p/10511167.html
今日推荐