多线程---同步函数的锁是this(转载)

时间:2022-09-16 20:56:52
class Ticket implements Runnable
{
private int tick = 100;
Object obj = new Object();
boolean flag = true;
public void run()
{
if(flag)
{
while(true)
synchronized(this)//注意这里的锁要一致
 //跟show()函数一样都是一个锁,show()锁是本身所以是this
 //同步的前提是:1、两个及其以上的线程;2、锁一样
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"同步代码块"+tick--);
}
}
}else
{
while(true)
show();
}
}
public synchronized void show()//锁是this
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"同步函数...."+tick--);
}
}
}
class ThisLock
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(10);}catch(Exception e){}
t.flag = false;
t2.start();
}
}