wait 方法及notify()練習題

2021-09-01 06:21:49 字數 1437 閱讀 9525

1.寫兩個執行緒,乙個執行緒列印 1~52,另乙個執行緒列印a~z,

列印順序是12a34b...5152z;

class printnumber implements runnable

@override

public void run() catch(interruptedexception e)}}

}}

}class printletter implements runnable

@override

public void run() catch(interruptedexception e)}}

}}public class test

}

2.編寫乙個程式,啟動三個執行緒,三個執行緒的名稱分別是 a,b,c;

每個執行緒將自己的名稱在螢幕上列印5遍,列印順序是abcabc...

class threada implements runnable

@override

public void run()

}}class threadb implements runnable

@override

public void run()

}}class threadc implements runnable

@override

public void run()

}}class printer

trycatch(interruptedexception e)

} public synchronized void printthreadb()

trycatch(interruptedexception e)

}public synchronized void printthreadc()

trycatch(interruptedexception e)

}}public class test

}

3.寫3個執行緒,列印如下

*thread-0

*thread-0@thread-1

*thread-0@thread-1#thread-2

*thread-0@thread-1#thread-2*thread-0

*thread-0@thread-1#thread-2*thread-0@thread-1

*thread-0@thread-1#thread-2*thread-0@thread-1#thread-2

...重複30次

class mythread

public void fun() {

thread thread1=new thread(new runnable() {

@override

public void run() {

for(int i=0;i

Notify與Wait方法使用(一)

一 基本使用 public class notifyandwait class mythread extends thread override public void run catch interruptedexception e system.out.println thread.curren...

wait 和notify 入門例子

也就是說,wait 會讓出物件鎖,同時,當前執行緒休眠,等待被喚醒,如果不被喚醒,就一直等在那兒。notify 並不會讓當前執行緒休眠,但會喚醒休眠的執行緒。先看第乙個例子!public class threadf catch interruptedexception e system.out.pr...

14 5 wait和notify方法 停止執行緒

wait 乙個執行緒如果執行了wait方法,那個該執行緒會進入乙個以鎖物件為識別符號的執行緒池中等待。等著中會釋放資源。notify 如果乙個執行緒開啟了notify方法,那麼久會喚醒以鎖物件為識別符號的執行緒中其中的乙個。notifyall 喚醒全部的執行緒。這個2個方法一定要用鎖物件來呼叫。st...