当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Could someone explain this code, it is related to threading

问题描述:

I am not able to understand how the control is transferring from "Expl Thread" output statement to the "Main Thread" output statement.

package com.myjava.threads;

class MyRunnableThread implements Runnable {

public static int myCount = 0;

public MyRunnableThread() {

}

public void run() {

while (MyRunnableThread.myCount <= 10) {

try {

System.out.println("Expl Thread: " + (++MyRunnableThread.myCount));

Thread.sleep(100);

} catch (InterruptedException iex) {

System.out.println("Exception in thread: " + iex.getMessage());

}

}

}

}

public class RunMyThread {

public static void main(String a[]) {

System.out.println("Starting Main Thread...");

MyRunnableThread mrt = new MyRunnableThread();

Thread t = new Thread(mrt);

t.start();

while (MyRunnableThread.myCount <= 10) {

try {

System.out.println("Main Thread: " + (++MyRunnableThread.myCount));

Thread.sleep(100);

} catch (InterruptedException iex) {

System.out.println("Exception in main thread: " + iex.getMessage());

}

}

System.out.println("End of Main Thread...");

}

}

The output is:

Starting Main Thread...

Main Thread: 1

Expl Thread: 2

Main Thread: 3

Expl Thread: 4

Main Thread: 5

Expl Thread: 6

Main Thread: 7

Expl Thread: 8

Main Thread: 9

Expl Thread: 10

Main Thread: 11

End of Main Thread...

网友答案:

how the control is transferring from "Expl Thread" output statement to the "Main Thread" output statement.

Control isn't being passed. Instead each thread is calling

Thread.sleep(100);

And as this is the same amount of time, they take turns. Change one of them to sleep(50) and you will see one prints messages twice as fast.

网友答案:

There is no control that is transferred... The threads are independently printing to the console every 100 milliseconds. Since the times are the same, then it appears they "take turns", but which "goes first" is not deterministic.

Change one of the Thread.sleep(100); values and you will see that one will take longer/shorter than the other to print.

网友答案:

That is something the thread scheduler decides. When you start the thread, it will run parallel with the other threads that are already there. Its up-to the thread scheduler to decide the order and the time allotted to each thread.

There is no guarantee on the order of execution.

分享给朋友:
您可能感兴趣的文章:
随机阅读: