public class TicketsSystem
{
public static void main(String args[])
{
SellTickets st=new SellTickets();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}
class SellTickets implements Runnable
{
int tickets=100;
public void run()
{
while(tickets>0)
{
if(tickets==1)
{
try{
Thread.sleep(10);
}catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println(tickets);
tickets--; }
}
}
最后四行输出结果是:
4
3
2
-2
我不明白的地方是:1,0,-1这三个数为什么没有输出呢?
{
public static void main(String args[])
{
SellTickets st=new SellTickets();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}
class SellTickets implements Runnable
{
int tickets=100;
public void run()
{
while(tickets>0)
{
if(tickets==1)
{
try{
Thread.sleep(10);
}catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println(tickets);
tickets--; }
}
}
最后四行输出结果是:
4
3
2
-2
我不明白的地方是:1,0,-1这三个数为什么没有输出呢?
public class TicketsSystem {
public static void main(String args[]) {
SellTickets st = new SellTickets();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}class SellTickets implements Runnable {
volatile int tickets = 100; public void run() {
while (tickets > 0) {
if (tickets == 1) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(tickets);
tickets--; }
}
}
我还是不懂原子性操作是意思?
同时你修改后的原代码我调试了下,结果跟我的还是一样.我想问的是:按照我的程序,为何没有输出1,0,-1这三个数呢?希望有一个真正的高手,把这个程序的执行过程讲一下,分不够的话,可以再加!
比如有三个线程(线程一,线程二,线程三)在走到System.out.println(tickets);之后,tickets--之前,它们的cpu分配时间刚好完了,此时tickets==4,换第四个线程,它打印出4,3,2以后,tickets==1,此时第四个线程进入sleep,然后第一个线程的cpu分配时间到了,执行tickets--,这时tickets==0,当它再次走到System.out.println(tickets);之前,它的cpu分配时间又完了,这时换第二个线程,它执行tickets--,此时tickets==-1,当它又再次执行到System.out.println(tickets);之前,此时它的cpu分配时间又完了,换第三个,它执行tickets--,此时tickets==-2,于是,继续执行,就有了LZ所看到的结果了。
啊宝说的很好的啊
volatile本来就是线程修改成员变量时 共享内存发生改变够 其他线程也同时得到修改后的值
实时系统的解决方法是:
java:声明方法为synchronized
C++:调用EnterCritcalSection
{
public static void main(String args[])
{
SellTickets st=new SellTickets();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}
class SellTickets implements Runnable
{
int tickets=100;
public void run()
{
while(true)
{
synchronized(this)
{
if(tickets>0)
{
try{
Thread.sleep(10);
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println(tickets);
tickets--;
}
}
}
}
}