多執行緒嘗試

2021-06-28 19:41:31 字數 2946 閱讀 2879

先貼**

package com.mult.test;

public class mythread

class runaablethread implements runnable catch (interruptedexception e)

system.out.println(thread.currentthread().getname() + " is selling ticket " + ticketcount);

ticketcount--;

}} }

}

先前寫了這樣的**來3個視窗來賣20張票。看似合理,但是問題來了,看輸出結果:

t3 is selling ticket 20

t1 is selling ticket 19

t2 is selling ticket 18

t2 is selling ticket 17

t3 is selling ticket 17

t1 is selling ticket 17

t1 is selling ticket 14

t3 is selling ticket 13

t2 is selling ticket 12

t1 is selling ticket 11

t3 is selling ticket 10

t2 is selling ticket 9

t3 is selling ticket 8

t1 is selling ticket 7

t2 is selling ticket 6

t1 is selling ticket 5

t3 is selling ticket 4

t2 is selling ticket 3

t3 is selling ticket 2

t1 is selling ticket 1

t2 is selling ticket 0

t3 is selling ticket -1

明明設定了>0的限制條件,為何會賣到0乃至-1?可以推想,當t1**掉最後一張票時,t2和t3已經進入了while迴圈。這是乙個執行緒同步的問題,共享的資源沒有被保護起來,導致t1,t2,t3同時操作去賣最後一張票。起初嘗試的是這樣的**來解決這個問題

package com.mult.test;

public class mythread

class runaablethread implements runnable catch (interruptedexception e)

//if(ticketcount > 0) }}

} }}

發現是不行的:將整個while迴圈用synchronized修飾,最先進入到while的執行緒將會佔據資源,直到賣完20張票:

t1 is selling ticket 20

t1 is selling ticket 19

t1 is selling ticket 18

t1 is selling ticket 17

t1 is selling ticket 16

t1 is selling ticket 15

t1 is selling ticket 14

t1 is selling ticket 13

t1 is selling ticket 12

t1 is selling ticket 11

t1 is selling ticket 10

t1 is selling ticket 9

t1 is selling ticket 8

t1 is selling ticket 7

t1 is selling ticket 6

t1 is selling ticket 5

t1 is selling ticket 4

t1 is selling ticket 3

t1 is selling ticket 2

t1 is selling ticket 1

目前的乙個笨辦法是:

package com.mult.test;

public class mythread

class runaablethread implements runnable catch (interruptedexception e)

synchronized(this) }}

} }}

只保護上面紅字的部分。這樣是可以實現同步賣票的:

t3 is selling ticket 20

t1 is selling ticket 19

t2 is selling ticket 18

t1 is selling ticket 17

t3 is selling ticket 16

t2 is selling ticket 15

t2 is selling ticket 14

t3 is selling ticket 13

t1 is selling ticket 12

t1 is selling ticket 11

t3 is selling ticket 10

t2 is selling ticket 9

t3 is selling ticket 8

t1 is selling ticket 7

t2 is selling ticket 6

t2 is selling ticket 5

t1 is selling ticket 4

t3 is selling ticket 3

t1 is selling ticket 2

t3 is selling ticket 1

不過更好的辦法肯定有,目前正在研究中。

多執行緒 嘗試Thread

這幾天用到多執行緒時才發現自己對多執行緒的了解少之又少,僅僅停留在lock上面,好了,我們知道 負載 是乙個很時尚,很牛x的玩意,往大處說,需要負載,資料庫需要負載。往小處說,執行緒也需要負載,面對海量的 使用者請求,我們的單執行緒肯定扛不住,那麼怎麼辦,一定要負載,所以說多執行緒是我們碼農必須要熟...

嘗試讓自己多執行緒

但是喜歡實現卻又是程式設計師的缺點,因為他們在實現一樣東西的時候,經常會不想去理會其他的事情。比如說,程式設計師接到一項任務時,普通的程式設計師就馬上會開始動手。稍微好一些的程式設計師則會仔細思考一下再動手。可惜,這樣子也是程式設計師管理能力欠缺的乙個原因。當你的能力足夠的時候,你應該懂得,把分配給...

嘗試讓自己多執行緒

但是喜歡實現卻又是程式設計師的缺點,因為他們在實現一樣東西的時候,經常會不想去理會其他的事情。比如說,程式設計師接到一項任務時,普通的程式設計師就馬上會開始動手。稍微好一些的程式設計師則會仔細思考一下再動手。可惜,這樣子也是程式設計師管理能力欠缺的乙個原因。當你的能力足夠的時候,你應該懂得,把分配給...