sleep方法會(huì)使當(dāng)前的線程暫停執(zhí)行一定時(shí)間(給其它線程運(yùn)行機(jī)會(huì))。讀者可以運(yùn)行示例1,看看結(jié)果就明白了。sleep方法會(huì)拋出異常,必須提供捕獲代碼。
實(shí)例一:
public class ThreadTest implements Runnable{
public void run(){
for(int k=0;k<5;k++){
if(k==2){
try{
Thread.currentThread().sleep(5000);
}
catch(Exception e){}
}
System.out.println(Thread.currentThread().getName()
+":"+k);
}
}
public static void main(String[] args){
Runnable r=new ThreadTest();
Threadt 1=new Thread(r,"t1_name");
Threadt 2=new Thread(r,"t2_name");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
t1被設(shè)置了最高的優(yōu)先級(jí),t2被設(shè)置了最低的優(yōu)先級(jí)。t1不執(zhí)行完,t2就沒有機(jī)會(huì)執(zhí)行。但由于t1在執(zhí)行的中途休息了5秒中,這使得t2就有機(jī)會(huì)執(zhí)行了。
實(shí)例二:
public class ThreadTest implements Runnable{
public synchronized void run(){
for(int k=0;k<5;k++){
if(k==2){
try{
Thread.currentThread().sleep(5000);
}
catch(Exceptione){}
}
System.out.println(Thread.currentThread().getName()
+":"+k);
}
}
publicstaticvoidmain(String[]args){
Runnable r=new ThreadTest();
Threadt 1=new Thread(r,"t1_name");
Threadt 2=new Thread(r,"t2_name");
t1.start();
t2.start();
}
}
請(qǐng)讀者首先運(yùn)行示例程序,從運(yùn)行結(jié)果上看:一個(gè)線程在sleep的時(shí)候,并不會(huì)釋放這個(gè)對(duì)象的鎖標(biāo)志。
join()方法:
join()方法,它能夠使調(diào)用該方法的線程在此之前執(zhí)行完畢。
實(shí)例a
public class ThreadTest implements Runnable{
public static int a=0;
public void run(){
for(intk=0;k<5;k++){
a=a+1;
}
}
public static void main(String[] args){
Runnable r=new ThreadTest();
Thread t=new Thread(r);
t.start();
System.out.println(a);
}
}
運(yùn)行結(jié)果不一定是5, 如果想讓 輸出的結(jié)果是5, 需要運(yùn)用join,
把上面的代碼改成如下:
public class ThreadTest implements Runnable{
public static int a=0;
public void run(){
for(intk=0;k<5;k++){
a=a+1;
}
}
public static void main(String[] args){
Runnable r=new ThreadTest();
Thread t=new Thread(r);
t.start();
t.join();
System.out.println(a);
}
}
測(cè)試一下以上的代碼即可,答案為輸出5.join()方法會(huì)拋出異常,應(yīng)該提供捕獲代碼。或留給JDK捕獲。