62,621
社区成员
发帖
与我相关
我的任务
分享
class ThreadDemo implements Runnable
{
private int ticket=10;
public synchronized void fun()
{
if(this.ticket>0)
{
try
{
//延迟操作,产生不同步的后果
Thread.sleep(100);
}
catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"卖票:----->"+this.ticket--);
}
}
public void run()
{
while(ticket>0)
{
this.fun();
}
}
}
public class ch03
{
public static void main(String[] args)
{
ThreadDemo d=new ThreadDemo();
Thread t1=new Thread(d,"售票点A");
Thread t2=new Thread(d,"售票点B");
Thread t3=new Thread(d,"售票点C");
t1.start();
t2.start();
t3.start();
}
}
class ThreadDemo implements Runnable
{
private int ticket=10;
public synchronized void fun()
{
if(this.ticket>0)
{
System.out.println(Thread.currentThread().getName()+"卖票:----->"+this.ticket--);
try
{
//延迟操作,产生不同步的后果
Thread.sleep(100);
}
catch (Exception e)
{
}
// System.out.println(Thread.currentThread().getName()+"卖票:----->"+this.ticket--);
}
}
public void run()
{
while(ticket>0)
{
this.fun();
}
}
}
搞定了,将注释地方的代码放到红色字体位置,就OK了,但是不知道什么原因
class ThreadDemo implements Runnable
{
private int ticket=10;
public synchronized void fun()
{
if(this.ticket>0)
{
System.out.println(Thread.currentThread().getName()+"卖票:----->"+this.ticket--);
try
{
//延迟操作,产生不同步的后果
Thread.sleep(100);
}
catch (Exception e)
{
}
// System.out.println(Thread.currentThread().getName()+"卖票:----->"+this.ticket--);
}
}
public void run()
{
while(ticket>0)
{
this.fun();
}
}
}
搞定了,将注释地方的代码放到红色字体位置,就OK了,但是不知道什么原因。