其他分享
首页 > 其他分享> > start() and run()两者有什么不同?

start() and run()两者有什么不同?

作者:互联网

public class Runner implements Runnable{
    @Override
    public void run() {
        System.out.println("CurrentThread Name:"+Thread.currentThread().getName());
        System.out.println("invoke run method");
    }
}

public class Starter implements Runnable{

    @Override
    public void run() {
        System.out.println("CurrentThread Name:"+Thread.currentThread().getName());
        System.out.println("invoke start method");
    }
}

public class TestStarterAndRunner {
    public static void main(String[] args) {
        Starter starter = new Starter();
        Runner runner = new Runner();

        Thread starterThread = new Thread(starter);
        Thread runnerThread = new Thread(runner);

        starterThread.start();
        runnerThread.run();
    }
}

===============================================
CurrentThread Name:main
invoke run method
CurrentThread Name:Thread-0
invoke start method

public class TestStarterAndRunner {
    public static void main(String[] args) {
        Starter starter = new Starter();

        Thread starterThread = new Thread(starter);

        starterThread.start();
        starterThread.start();
    }
}

================================================
Exception in thread "main" java.lang.IllegalThreadStateException
	at java.lang.Thread.start(Thread.java:710)
	at com.rookie.concurrent.TestStarterAndRunner.main(TestStarterAndRunner.java:15)
CurrentThread Name:Thread-0
invoke start method
public class TestStarterAndRunner {
    public static void main(String[] args) {
        Runner runner = new Runner();

        Thread runnerThread = new Thread(runner);

        runnerThread.run();
        runnerThread.run();
    }
}

===============================================
CurrentThread Name:main
invoke run method
CurrentThread Name:main
invoke run method

标签:run,Thread,两者,start,new,main,public
来源: https://www.cnblogs.com/masker99/p/16139581.html