本帖最后由 杜光 于 2013-7-28 09:28 编辑
- package qbb;
- class Ticket implements Runnable{
- private int ticketNo = 100;
- public void run(){
- while(true){
- Object obj = new Object();
- synchronized(obj){
- if(ticketNo > 0){
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName() + "\t"
- + ticketNo-- + " has been saled");
- }
- }
- }
- }
- }
- public class Test{
- 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();
- }
- }
复制代码 用eclipse运行后,结果中仍然出现0,-1,-2等错票,为什么呢? |