同步锁与同步函数锁的使用方法

class Ticket implements Runnable
{
private int num=300;
//Object obj = new Object();
    boolean flag=true;
public void run()
{
if(flag)
while(true)
{
synchronized(this)
{
if(num>0)
{
try{Thread.sleep(10);}
catch (InterruptedException e){}
System.out.println("...obj..."+num--);
}
}    
}
else
while(true)
{
show();
}
}
public synchronized void show()
{
if(num>0)
{
try{Thread.sleep(10);}
catch (InterruptedException e){}
System.out.println("...function..."+num--);
}
}


}
class  ThreadDemo
{
public static void main(String[] args) 
{
System.out.println("Hello World!");
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
try{Thread.sleep(20);}
catch (InterruptedException e){}
t.flag=false;
t2.start();
}
}
经验分享 程序员 微信小程序 职场和发展