Thread的Sleep方法詳解,

/*
1.Thread.sleep(毫秒)
2.sleep方法是一個靜態方法
3.該方法的作用:阻塞該線程,讓給其他線程
*/
public class fuck4 {
public static void main(String[] args) throws InterruptedException{
Thread t1=new professor();
t1.setName("t1");
t1.start();

//阻塞主線程
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"-->"+i);
Thread.sleep(500);
}
}

}

class professor extends Thread{
//Thread中的run方法不拋出異常,所以重寫run方法後,在run方法的聲明位置上不能使用throw
//必須使用try catch
public void run(){
for(int i=0;i<50;i++){
System.out.println(Thread.currentThread().getName()+"-->"+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
//m1();
}
//public static void m1 throws Exception(){}//m1可以拋出異常

}


/*
面試題
*/
public class fuck5 {
public static void main(String[] args) throws InterruptedException{
//創建線程
Thread t=new processor();
t.setName("t");

//啓動線程
t.start();

//休眠
t.sleep(5000);//等同於Thread.sleep(5000).阻塞的還是當前線程,和t線程無關
System.out.println("hello java");

A a=null;
a.m1();//不會報空指針異常,空指針異常是指空指針指向對象,m1爲靜態方法,不是對象
}

}


class processor extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"--->"+i);
}
}
}


class A{
public static void m1(){}

}

/*
某線程正在休眠,如何打斷它的休眠

以下方法依靠的是異常處理機制
*/
public class fuck6{
public static void main(String[] args) throws InterruptedException{
Thread t=new Thread(new processor());
t.setName("t");
t.start();

//5s之後終止
Thread.sleep(5000);

//打斷t的休眠
t.interrupt();

}
}
class processor implements Runnable{
public void run(){
try{
Thread.sleep(1000000);
System.out.println("heetian");}
catch(InterruptedException e){
e.printStackTrace();}

  for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"--->"+i);
}
}

}

/*
如何正確更好的終止一個正在執行的線程

需求:線程啓動5s之後終止
*/
public class fuck7{
public static void main(String[] args) throws InterruptedException{

processor p=new processor();
Thread t=new Thread(p);

t.setName("t");
t.start();

//5s之後終止
Thread.sleep(5000);

//終止
p.run=false; 
//因爲線程是同時運行的,主線程和t線程同時運行,主線程5秒後run變成false,
//這時t線程剛好輸出五個數,但已經不滿足run=true條件,所以就終止了,究極原因是線程是同時運行的
}
}


class processor implements Runnable{
boolean run=true;

public void run(){

for(int i=0;i<10;i++){
if(run){
try{Thread.sleep(1000);}catch(InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"--->"+i);}
else{
return;}

}
}
}

發佈了110 篇原創文章 · 獲贊 8 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章