Why does the FirstThread always run before the SecondThread in the following code?

前端 未结 2 1920
不思量自难忘°
不思量自难忘° 2020-12-21 14:04
public class TowThreads {
    public static class FirstThread extends Thread {
        public void run() {
            for (int i = 2; i < 100000; i++) {
                 


        
相关标签:
2条回答
  • 2020-12-21 14:53

    Use start not run

    public static void main(String[] args) {
            new FirstThread().start();
            new SecondThread().start();
        }
    

    If you use run method, you call first method and after second method. If you want to run parallel threads, you must use start method of thread.

    0 讨论(0)
  • 2020-12-21 15:00

    Well it depends on the machine processor and jvm how they schedule your threads. Even in the article you have read it is clearly mentioned

    "Not only may the results vary from machine to machine, but running the same program multiple times on the same machine may produce different results. Never assume one thread will do something before another thread does, unless you've used synchronization to force a specific ordering of execution"

    you can't expect threads to behave in same way on all machines. It all depends how the machine schedules them.

    0 讨论(0)
提交回复
热议问题