本文實例講述了java線程等待用法。分享給大家供大家參考,具體如下:
線程等待
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
public class hello { public static void main(string[] args) { a a = new a(); new thread( new myrun(a)).start(); new thread( new myrun1(a)).start(); } } class myrun implements runnable { private a a; public myrun(a a) { this .a = a; } @override public void run() { synchronized (a) { a.settitle( "hello" ); try { a.wait(); } catch (interruptedexception e) { e.printstacktrace(); } a.setnumber( 12 ); system.out.println(a); } } } class myrun1 implements runnable { private a a; public myrun1(a a) { this .a = a; } @override public void run() { synchronized (a) { a.settitle( "world" ); a.setnumber( 24 ); a.notifyall(); system.out.println(a); } } } class a { private string title; private integer number; public string gettitle() { return title; } public void settitle(string title) { this .title = title; } public integer getnumber() { return number; } public void setnumber(integer number) { this .number = number; } @override public string tostring() { return "a{" + "title='" + title + '\ '' + ", number=" + number + '}' ; } } |
運行輸出:
a{title='world', number=24}
a{title='world', number=12}
線程等待,obj.wait()
,會釋放當前的鎖,對象的普通方法,obj.wait(超時時間)
,表示指定時間后可以自動喚醒
線程喚醒,obj.notify()
,喚醒一個線程,obj.notifyall()
,喚醒所以線程,obj需要和線程等待的對象一致。
wait和sleep的區別
個人認為:sleep就是一種延緩代碼執行的方法,wait是有關多線程的一些高級操作。
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://blog.csdn.net/shuair/article/details/81943569