本文介紹了多線程實(shí)現(xiàn)多個(gè)窗口售票問題的兩種枷鎖方式, 分別是synchronized 和lock()和unlock()
具體代碼如下:
第一種:
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
|
package runnable; import java.util.concurrent.locks.lock; import java.util.concurrent.locks.reentrantlock; /* * 同步 * 這里有兩種方式加鎖 * 分別是 * 1.synchronized * 2.lock()和unlock() */ public class myrunnable implements runnable { private int tickets = 100 ; // 定義鎖 private lock lock = new reentrantlock(); public void run() { while ( true ) { // 加鎖 lock.lock(); if (tickets > 0 ) { try { thread.sleep( 100 ); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println(thread.currentthread().getname() + "售出了第" + (tickets--) + "張票" ); } lock.unlock(); } } } |
結(jié)果:
第二種:
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
|
package runnable; /* * 同步 * 這里有兩種方式加鎖 * 分別是 * 1.synchronized * 2.lock()和unlock() */ public class myrunnable implements runnable { private int tickets = 100 ; public void run() { while ( true ) { synchronized ( this ) { if (tickets > 0 ) { try { thread.sleep( 100 ); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println(thread.currentthread().getname() + "售出了第" + (tickets--) + "張票" ); } } } } } |
結(jié)果:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package runnable; public class runnabledemo { public static void main(string[] args) { myrunnable myrunnable = new myrunnable(); thread t1 = new thread(myrunnable, "窗口一" ); thread t2 = new thread(myrunnable, "窗口二" ); thread t3 = new thread(myrunnable, "窗口三" ); t1.start(); t2.start(); t3.start(); } } |
不知道是巧合還是怎么回事,運(yùn)行這兩個(gè)多線程小實(shí)例的時(shí)候,電腦突然卡了起來,我趕緊把eclipse關(guān)了。
有關(guān)于結(jié)束進(jìn)程的語句并沒有添加,自行參閱吧。
以上就是本文關(guān)于java多線程窗口售票問題實(shí)例的全部?jī)?nèi)容,希望對(duì)打擊有所幫助。如有問題可以隨時(shí)留言,期待您的寶貴意見。
原文鏈接:https://www.cnblogs.com/neuhao/p/6485573.html