/*
同步函数 用的锁是this
可以将同步代码块 传入的对象为this 则同步代码块和同步函数调用了同一个锁
同步函数和同步代码块的区别:
同步函数的锁是固定的this(当前对象)
同步代码块的锁是任意对象
建议使用同步代码块
*/
/*
*/
class Ticket implements Runnable{
private int num=100;
Object obj=new Object();
public void run(){
while(true){
// synchronized(obj){
show
// }
}
}
public synchronized void show(){//同步的第二种表现形式 同步代码块
if(num>0){
try{
Thread.sleep(10);
}
catch(InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"--sale="+num--);
}
}
}
class SynFuctionDemo1{
public static void main(String[] args) {
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
t1.start();
t2.start();
t3.start();
}
}
Java 同步函数
最新推荐文章于 2021-02-16 19:19:54 发布