大家好,我是学习java的新手,下面关于线程的问题有点搞不明白
下面是我的一个小程序,但是我每次运行出来的结果却不一样?这是为什么呢?
问题2:如果线程1占有了cpu,执行了run()方法,不是会一直循环到ticket=0才停止的么?
如果是这样的话,那线程2,线程3,线程4不是没有机会调用run()方法运行了?
问题3:如果这么随机运行的话,我们通过什么来控制多线程按我们想要的方式运行呢?
先谢谢大家帮忙,谢谢了
public class TicketSystem {
public static void main(String[] args) {
SellTicket st=new SellTicket();
new Thread(st).start();//线程1
new Thread(st).start();//线程2
new Thread(st).start();//线程3
new Thread(st).start();//线程4
}
}
class SellTicket implements Runnable
{
int ticket=20;
public void run()
{
while(true)
{
if(ticket>0)
{
try{
Thread.sleep(100);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"Have sold tickets "+ticket);
ticket--;
}
}
}
}
我的运行结果如下:
Thread-1Have sold tickets 20
Thread-0Have sold tickets 20
Thread-2Have sold tickets 20
Thread-3Have sold tickets 17
Thread-1Have sold tickets 16
Thread-2Have sold tickets 16
Thread-0Have sold tickets 16
Thread-3Have sold tickets 13
Thread-2Have sold tickets 12
Thread-0Have sold tickets 11
Thread-1Have sold tickets 10
Thread-3Have sold tickets 9
Thread-0Have sold tickets 8
Thread-1Have sold tickets 8
Thread-2Have sold tickets 8
Thread-3Have sold tickets 5
Thread-0Have sold tickets 4
Thread-1Have sold tickets 4
Thread-2Have sold tickets 4
Thread-3Have sold tickets 1
Thread-0Have sold tickets 0
Thread-1Have sold tickets -1
Thread-2Have sold tickets -2