Order of thread execution in Java

女生的网名这么多〃 提交于 2020-01-25 05:12:04

问题


I have doubts about order of Thread execution in java. This example

  public class Thr implements Runnable {
    String string = "Yes ";
    public void run(){
      this.string = "No ";
    }
    public static void main (String args[]){
      Thr t = new Thr();
      new Thread(t).start();
      for(int i = 0; i < 10; i++)
          System.out.println(t.string);
    } 
  }

gives output :

Yes 
No 
No 
No 
No 
No 
No 
No 
No 
No 

I have red this topic Java. The order of threads execution and I am confused why string is changed to no after first pass through for loop. I tought that , as main thread doesn't have large job to do, main thread will execute first, and that output will be

Yes 
Yes 
Yes 
Yes 
Yes 
Yes 
Yes 
Yes 
Yes
No

When I put some print in run method instead this.string = "No" then, print from run method prints last.


回答1:


I think that I figured out what is happening. Thing is, that this threads , main thread and new Thread(t) are both executing parallely. And it is kind of lottery, because they both make request for processor time, so, as main thread begin to execute, with all code that it needs to execute, main thread spend processor time, and it only prints first yes, and then new Thread(t) gets his processor time, changes "yes" to no, and finish execution, and than main thread again continue to execute. I've made a little test, and in

public class Thr implements Runnable {
  String string = "Yes ";
  public void run(){
    this.string = "No ";
  }
  public static void main (String args[]){
  Thr t = new Thr();
  Thread tr = new Thread(t);
  tr.start();
  for(int i = 0; i < 10; i++)
      System.out.println(t.string + tr.isAlive());
  } 
}

and the output is

Yes true
No false
No false
No false
No false
No false
No false
No false
No false
No false



回答2:


When working with threads be sure of one thing, you can't predict when a thread will start even if you call this:

new Thread(t).start();

When you call it the thread enter in a state that is "Ready to start running or Runnable state" and then the thread scheduler can take the thread and put it in a running state IF HE WANTS, it's a little bit complex but you can't predict what will happen when you have a bunch of them, sometimes if you start two threads the last would run first. For more understanding of the topic see this



来源:https://stackoverflow.com/questions/38234138/order-of-thread-execution-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!