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

来源:互联网 发布:足球新闻数据app 编辑:程序博客网 时间:2024/05/10 03:11
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();
}
}
0 0
原创粉丝点击