java创建多个线程为什么只有一个线程运行?
PHP中文网
PHP中文网 2017-04-17 13:15:21
0
3
946

新手问个简单的问题:
为什么以下代码运行结果是这样的呢?

Thread-0出售票20
Thread-0出售票19
Thread-0出售票18
Thread-0出售票17
Thread-0出售票16
Thread-0出售票15
Thread-0出售票14
Thread-0出售票13
Thread-0出售票12
Thread-0出售票11
Thread-0出售票10
Thread-0出售票9
Thread-0出售票8
Thread-0出售票7
Thread-0出售票6
Thread-0出售票5
Thread-0出售票4
Thread-0出售票3
Thread-0出售票2
Thread-0出售票1

public class ThreadDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread t = new TestThread();
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
    }
}

class TestThread implements Runnable {
    private int tickets = 20;
    public void run() {
        while(true) {
            if(tickets>0)
                System.out.println(Thread.currentThread().getName()+"出售票"+tickets--);
        }
    }
}
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
黄舟

This should not happen if you run it a few more times. If you change system.out to write to a file, it will definitely output multi-threaded output.
It should be related to the thread scheduling of the virtual machine. If the second thread has not started before the completion of 20 cycles, of course only thread-0 will run. If the subsequent thread starts before the end of 20 runs, it will There will be multiple threads outputting. If you try changing to 2000, there will definitely be a lot of threads outputting.

洪涛
t.wait()  
不wait的话 线程0跑完了就退出了
左手右手慢动作
    public class ThreadDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new TestThread().start();
        new TestThread().start();
        new TestThread().start();
        new TestThread().start();
    }
}

class TestThread extends Thread {
    private int tickets = 20;
    public void run() {
        while(true) {
            if(tickets>0)
                System.out.println(Thread.currentThread().getName()+"出售票"+tickets--);
            else
                break;
        }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template