day 6 - 线程和synchronized(part 2)

121 阅读1分钟

前面说过,runnable中的run才是线程最终要执行的内容

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("this is my thread");
    }
}
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("this is my runnable");
    }
}

实例化

public static void main(String[] args) {
    MyThread myThread = new MyThread();
    Thread myRunnable = new Thread(new MyRunnable());
    System.out.println("main Thread begin");
    myThread.start();
    myRunnable.start();
    System.out.println("main Thread end");
}

输出

main Thread begin
main Thread end
this is my thread
this is my runnable

最后的打印打印在线程run之前,主线程不需要等待子线程完成

值得注意,线程不可以直接调用 run(),直接调用 run() 不会创建线程,而是主线程直接执行 run() 的内容,相当于执行普通函数。

public static void main(String[] args) {
    MyThread myThread = new MyThread();
    Thread myRunnable = new Thread(new MyRunnable());
    System.out.println("main Thread begin");
    myThread.run();
    myRunnable.run();
    System.out.println("main Thread end");
}

输出

main Thread begin
this is my thread
this is my runnable
main Thread end

参考资料:juejin.cn/post/684490…