使用runnable實現數據共享,供大家參考,具體內容如下
先上代碼:
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
|
public class testthread { private static final logger logger = loggerfactory.getlogger(testthread. class ); private final class myrunnable implements runnable { private int i; public myrunnable() { this .i = 10 ; } public void run() { while (i > 0 ) { synchronized ( this ) { if (i > 0 ) { i--; logger.debug( "{} buy one ticket, {} left. " , thread.currentthread().getname(), i); } } } } } @test public void testrunable() throws interruptedexception{ myrunnable myrunnable = new myrunnable(); thread th1 = new thread(myrunnable); thread th2 = new thread(myrunnable); th1.start(); th2.start(); th1.join(); th2.join(); } } |
樓上的代碼很簡單,模擬一個售票系統。通過兩個thread對象開啟兩條線程同時運行一個myrunnable實例。
幾個注意點:
1. 沒有加上synchronised關鍵詞的話,即
1
2
3
4
5
6
7
8
|
public void run() { while (i > 0 ) { if (i > 0 ) { i--; logger.debug( "{} buy one ticket, {} left. " , thread.currentthread().getname(), i); } } } |
系統的運行結果:
1
2
3
4
5
6
7
8
9
10
|
thread- 1 buy one ticket, 8 left. thread- 2 buy one ticket, 8 left. thread- 2 buy one ticket, 6 left. thread- 1 buy one ticket, 6 left. thread- 2 buy one ticket, 5 left. thread- 1 buy one ticket, 4 left. thread- 2 buy one ticket, 3 left. thread- 1 buy one ticket, 2 left. thread- 2 buy one ticket, 1 left. thread- 1 buy one ticket, 0 left. |
可以看到,缺少同步的程序輸出明顯有問題。
2. 在進入同步代碼塊之后,還需要對i的值再進行一次判斷,即,如果不加if判斷:
1
2
3
4
5
6
7
8
9
|
public void run() { while (i > 0 ) { synchronized ( this ) { i--; logger.debug( "{} buy one ticket, {} left. " , thread.currentthread().getname(), i); } } } |
程序的運行結果為:
1
2
3
4
5
6
7
8
9
10
11
|
thread- 2 buy one ticket, 9 left. thread- 2 buy one ticket, 8 left. thread- 2 buy one ticket, 7 left. thread- 2 buy one ticket, 6 left. thread- 2 buy one ticket, 5 left. thread- 2 buy one ticket, 4 left. thread- 2 buy one ticket, 3 left. thread- 2 buy one ticket, 2 left. thread- 2 buy one ticket, 1 left. thread- 2 buy one ticket, 0 left. thread- 1 buy one ticket, - 1 left. |
可以看出,出現了“多賣”的現象, 所以需要在進入同步代碼塊中再進行一次if判斷。
總結
synchronised用于互斥訪問共享變量, 并在同步代碼塊中使用if判斷更新共享變量。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/NewUser2771894007/article/details/79630721