简体   繁体   中英

java - Thread.sleep

In the code and output below, t2 doesn't start until t1 finishes. Shouldn't they work parallel? Is Thread.sleep() affect whole process?

public class Main {

    public static void main(String[] args) {

        T t1 = new T(), t2 = new T();

        t1.run();
        t2.run();
    }
}

class Test {

    private int x;

    void foo() {

        synchronized (this){
            System.out.println("Entered");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Exit");
        }
    }
}

class T extends Thread {

    static Test t = new Test();

    public void run() {

        System.out.println("Thread started");
        t.foo();
    }

}

Output:

Thread started

Entered

Exit

Thread started

Entered

Exit

If you want to run these as separate threads, you need to call the Thread.start() method.

Instead, you're calling the run() method directly. The two calls will execute in the same thread as the caller.

As an aside, usually you can just subclass Runnable rather than Thread. Then you can choose to pass your Runnable to the Thread(Runnable) constructor -- or to an ExecutorService .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM