同步程式碼塊(同步監視器)
阿新 • • 發佈:2022-04-19
同步程式碼塊(同步監視器)
-
第一種情況:實現介面Runnable方法
程式碼塊鎖synchronized的this指的是同一個demo012;
package com.Thread; public class Demo012 implements Runnable { int ticket = 10; @Override public void run() { int ti = 1; for (int people = 100; people > 0; people--) { //做一個實時執行緒監控器;鎖定一個程式碼塊;防止多執行緒爭奪一個資源 synchronized (this) {//這個this指呼叫他的物件demo012 if (ticket > 0) { System.out.println("我搶到了第" + ticket-- + "張票;從" + Thread.currentThread().getName() + "視窗"); } } } } }
package com.Thread; public class Demo011 { public static void main(String[] args) { Demo012 demo012 = new Demo012(); Thread thread = new Thread(demo012,"1號"); thread.start(); Thread thread2 = new Thread(demo012,"2號"); thread2.start(); Thread thread3 = new Thread(demo012,"3號"); thread3.start(); } }
-
第二種情況:繼承方法Thread方法
這裡,我們用到位元組碼檔案來鎖定監視對應的執行緒
package com.Thread; public class TrainTicket extends Thread{ static int trainticket =10; public TrainTicket(String name) { super(name); } public void run() { //做一個執行緒同步監視器;this一個程式碼塊有3個物件;這裡TrainTicket的位元組碼唯一性 synchronized(TrainTicket.class){ for(int i = 1;i<=100;i++){//有100人在搶票 if(trainticket>0){ System.out.println("我搶到了火車票;第"+trainticket--+"張;從"+this.getName()+"視窗"); } } } } }
package com.Thread;
public class Demo001 {
public static void main(String[] args) {
TrainTicket trainTicket1 = new TrainTicket("1號");
trainTicket1.start();
TrainTicket trainTicket2 = new TrainTicket("2號");
trainTicket2.start();
TrainTicket trainTicket3 = new TrainTicket("3號");
trainTicket3.start();
}
}