Java多執行緒中,synchronized同步程式碼塊解決多執行緒資料安全問題
阿新 • • 發佈:2020-12-05
synchronized(任意物件):就相當於給程式碼加鎖了,任意物件就可以看成是一把鎖。
synchronized(任意物件)
{
多條語句操作共享資料的程式碼
}
程式碼演示
public class SellTicket implements Runnable {
private int tickets=100;
private Object obj = new Object();
@Override
public void run() {
while(true){
synchronized (obj){
if(tickets>0){
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +"正在出售第"+tickets+"張票");
tickets--;
}
}
}
}
}
public class SellTicketDemo {
public static void main(String[] args) {
SellTicket st= new SellTicket();
Thread t1=new Thread(st,"視窗1");
Thread t2=new Thread(st,"視窗2");
Thread t3=new Thread(st,"視窗3");
t1.start();
t2.start();
t3.start();
}
}