1. 同步**塊
synchronized
(物件)
例程
package cn.wf.thread1;
/** * 多執行緒同步:同步**塊
* @author wf
* */
public
class
thread_test
}class
thread01
implements
runnable
trycatch
(interruptedexception e)
system.out.
println
(thread.
currentthread()
.getname()
+"出票"
+tickets)
; tickets -=1;
}}}}
執行結果
thread-
0出票5
thread-
0出票4
thread-
0出票3
thread-
0出票2
thread-
0出票1
2. 同步方法
訪問控制符 synchronized 返回值型別 方法名(引數)
例程
package cn.wf.thread1;
/** * 多執行緒同步:同步方法
* @author wf
* */
public
class
thread_test02
}class
thread02
implements
runnable
}private
synchronized
void
sale()
catch
(interruptedexception e)
system.out.
println
(thread.
currentthread()
.getname()
+"出票"
+tickets)
; tickets -=1;
}}}
執行結果
thread-
0出票5
thread-
0出票4
thread-
0出票3
thread-
0出票2
thread-
0出票1
java多執行緒 同步
2019獨角獸企業重金招聘python工程師標準 synchronized關鍵字鎖的物件可以是方法 變數 類和當前例項。synchronized不能被繼承,子類將自動去除synchronized關鍵字 public synchronized void 變為public void 方法public s...
java多執行緒值執行緒同步
在多執行緒的操作中,多個執行緒有可能同時處理同一資源,這就是多執行緒的共享資料。如下程式 public class threaddemo catch interruptedexception e catch interruptedexception e catch interruptedexcept...
Java多執行緒 同步(一)
可能我們在開發專案進行過程中,通常會冒出這樣的困惑 應該選擇效率,還是選擇質量?會不會有偷懶的思維,覺得把一些摸不清頭緒,不知道怎麼寫的 片段去掉,可以節省許多時間,更早的完成專案計畫,其實以前我也是這麼想的,但最近我開始意識到,這個問題的糾結之處不在於選擇困難,而在於問題本身是個偽命題。什麼是 質...