同步代码块
锁多条语句操作共享数据,可以使用同步代码块实现。
格式:
synchronized(任意对象){
多条语句操作共享数据
}
synchronized(任意对象):相当于给代码加锁了,任意对象看成一把锁。
卖票案例:
public class SellTickerDemo {
public static void main(String[] args) {
SellTicker st = new SellTicker();
Thread t1 = new Thread(st,"窗口1");
Thread t2 = new Thread(st,"窗口2");
Thread t3 = new Thread(st,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
class SellTicker implements Runnable{
private static int tickerNum = 100;
private Object obj = new Object();
@Override
public void run(){
while (true){
synchronized(obj){
if(tickerNum>0){
System.out.println(Thread.currentThread().getName()+":卖出第"+tickerNum+"号票,"+"当前剩余票数:"+(tickerNum-1));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickerNum--;
}
}
}
}
}
同步的好处和弊端:
好处:解决了多线程安全的问题;
弊端: 当线程很多时,因为每个线程都要去判断同步上的锁,很耗费资源,降低了程序的运行效率。