1. 程式人生 > >多執行緒示例模仿

多執行緒示例模仿

public class Test {


public static void main(String[] args) {
ThreadT tt = new ThreadT();
Thread t1 = new Thread(tt, "t1");
Thread t2 = new Thread(tt, "t2");
Thread t3 = new Thread(tt, "t3");
t1.start();
t2.start();
t3.start();
}
}


class ThreadT extends Thread{

int ticket = 10;

public void run(){

while(ticket > 0){
synchronized(this){
this.buyTicket();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

public void buyTicket(){
if(ticket > 0){
System.out.println(Thread.currentThread().getName()+"=========第" + ticket + "張票===========");
ticket -=1;
}
}

}

執行緒如果要接入主執行緒的話就用join方法,該執行緒就會合併入主執行緒

yield():暫停當前正在執行的執行緒物件,並執行其他執行緒