liang lei liang lei - 1 year ago 73
Java Question

i want to test java multithread ,but only one thread run

public class ThreadText
public static void main(String[] args)
windows w=new windows();
Thread t1=new Thread(w);
Thread t2=new Thread(w);
Thread t3=new Thread(w);
Thread t4=new Thread(w);/*four threads*/

i want to use four windows to sale 1000 tickets

class windows implements Runnable
int tickets=1000;
public void run()
System.out.println(Thread.currentThread().getName()+" is saling"+tickets);
}/*i think problem is here*/

when i don't use synchronized ,all threads run,but results are wrong


Answer Source

When you synchronize the entire loop, the first thread will get the lock and will count down to 0. The other 3 threads will wait until first thread releases the lock, at which point there's nothing left for them to do. In effect, the result is single-threaded.

To work correctly, you need to synchronize inside the loop, so the other threads can work too.

However, the first thread may still be too fast, so that it ends up doing all the work. To better simulate what you want, add a delay outside the synchronize block (making a sale takes time, you know). Added minimum delay of 1ms in the code below.

And finally, Java naming convention is for class names to start with an Uppercase letter, so it should be named Windows.

class Windows implements Runnable {
    private int tickets = 1000;
    public void run() {
        String threadName = Thread.currentThread().getName();
        for (;;) { // loop forever
            synchronized (this){
                if ( == 0)
                System.out.println(threadName + " is saling " +;
            try {
            } catch (InterruptedException e) {


Thread-0 is saling 1000
Thread-2 is saling 999
Thread-3 is saling 998
Thread-1 is saling 997
Thread-0 is saling 996
Thread-1 is saling 995
Thread-2 is saling 994
Thread-3 is saling 993
Thread-0 is saling 992
Thread-1 is saling 991
Thread-3 is saling 990
Thread-2 is saling 989
        . . .
Thread-2 is saling 11
Thread-1 is saling 10
Thread-0 is saling 9
Thread-3 is saling 8
Thread-0 is saling 7
Thread-1 is saling 6
Thread-2 is saling 5
Thread-1 is saling 4
Thread-0 is saling 3
Thread-3 is saling 2
Thread-2 is saling 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download