可以通過線程的方法進行基本的線程控制,除了已知的start、run、sleep方法外還有isAlive、currentThread、interrupt方法。
isAlive:該方法用來測試線程是否處於活動狀態。線程由start方法啟動後,直至被終止之間的任何時刻都處於Alive狀態。當處於新建狀態和死亡狀態時,該方法返回false。
currentThread:該方法是Thread類的的類方法,返回正在使用CPU資源的線程。
interrupt:當線程處於休眠狀態時,一個占有CPU資源的線程可以讓休眠的線程調用interrupt方法喚醒自己,導致休眠的線程發生InterruptedException異常結束休眠,重新排隊等待CPU資源。
class A implements Runnable{
Thread student,teacher;
A(){
teacher=new Thread(this,"王教授");
student=new Thread(this,"張三");
}
public void run(){
if(Thread.currentThread()==student){
try{
System.out.println(student.getName()+"正在睡覺,不聽課");
Thread.sleep(1000*60*60);
}catch(InterruptedException e){
System.out.println(student.getName()+"被老師叫醒了");
}
}
else if(Thread.currentThread()==teacher){
for(int i=1;i<=3;i++){
System.out.println("上課!");
}try{
Thread.sleep(500);
}catch(InterruptedException e){}
student.interrupt();
}
}
}
public class BasicControlThread{
public static void main(String args[]){
A a=new A();
a.student.start();
a.teacher.start();
}
}
此外還有stop和join方法
stop():通過調用線程的實例方法stop()來終止線程,終止後即進入死亡狀態,不能再被調度。
join():一個線程在占有CPU資源期間,可以讓其他線程調用join()方法和本線程聯合。當前線程等待調用該方法線程結束後,再重新排隊等待CPU資源,以便恢復執行。
class TV{
float price;
String name;
TV(String name,float price){
this.price=price;
this.name=name;
}
}
class ThreadJoin implements Runnable{
TV tv;
Thread customer,tvMaker;
ThreadJoin(){
customer=new Thread(this,"顧客");
tvMaker=new Thread(this,"電視制造商");
}
public void run(){
if(Thread.currentThread()==customer){
System.out.println(customer.getName()+"等"+tvMaker.getName()+"生產電視機");
try{
tvMaker.join();//線程customer開始等待tvMaker結束
}catch(InterruptedException e){ }
System.out.println(customer.getName()+"買了一台電視機"+tv.name+"價格:"+tv.price);
}
else if(Thread.currentThread()==tvMaker){
System.out.println(tvMaker.getName()+"開始生產電視機...");
try{
tvMaker.sleep(2000);
}catch(InterruptedException e){ }
tv=new TV("長虹牌",4500);
System.out.println(tvMaker.getName()+"生產完畢!!!");
}
}
}
public class JoinThread{
public static void main(String args[]){
ThreadJoin th=new ThreadJoin();
th.customer.start();
th.tvMaker.start();
}
}