这是个模拟卖票的问题,使用一个对象实现Runnable接口建立四个线程,这个对象有100张票,四个进程同时卖,因为没使用锁,所以会出现负数票,但是为什么会出现相同的票呢?8号票卖了四次,是因为成员变量在if之后进栈保存了值?然后直接用这个num输出吗?
代码:
class Ticket implements Runnable//extends Thread
{
private int num = 100 public void run()//这时不能抛出异常,因为覆盖的原函数没有抛出异常,必须catch
{
while(true)
{
if(num>0)
{
try{
Thread.sleep(2);
}
catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+" sale "+num--);
}
else break;
}
}
}
class Demo
{
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);
Thread t4=new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}部分输出
Thread-1 sale 12 Thread-0 sale 13 Thread-0 sale 10 Thread-1 sale 9 Thread-3 sale 9 Thread-2 sale 10 Thread-2 sale 8 Thread-1 sale 8 Thread-0 sale 8 Thread-3 sale 8 Thread-2 sale 7 Thread-1 sale 6 Thread-0 sale 5 Thread-3 sale 4 Thread-2 sale 3 Thread-1 sale 2 Thread-0 sale 1 Thread-3 sale 0 Thread-2 sale -1 Thread-1 sale -2
慕无忌1623718
噜噜哒
函数式编程
随时随地看视频慕课网APP
相关分类