mon*_*dle 1 java multithreading operating-system
为什么每次运行此程序时输出的顺序都不同?是否由于多个线程同时尝试访问共享资源.因此,线程执行的方式是随机的吗?
我的输出
java MyThreadExample Hello from thread 1 Hello from thread 3 Hello from thread 4 Hello from thread 2
java MyThreadExample Hello from thread 1 Hello from thread 3 Hello from thread 4 Hello from thread 4
java MyThreadExample
Hello from thread 1
Hello from thread 4
Hello from thread 3
Hello from thread 2
Run Code Online (Sandbox Code Playgroud)
码:
import java.io.*;
import java.lang.*;
class MyThreadExample {
public static void main(String[] args) {
HelloThread ht1 = new HelloThread(1);
HelloThread ht2 = new HelloThread(2);
HelloThread ht3 = new HelloThread(3);
HelloThread ht4 = new HelloThread(4);
ht1.start();
ht2.start();
ht3.start();
ht4.start();
}
}
class HelloThread extends Thread {
int threadID;
HelloThread(int threadID) {
this.threadID = threadID;
}
public void run() {
System.out.println("Hello from thread " + this.threadID);
}
} // end Thread
Run Code Online (Sandbox Code Playgroud)
你是绝对正确的,这是因为多线程.
你开始了4个线程,每个线程都是自己的 - 它们之间没有逻辑顺序,因此它们中的任何一个都可以先完成,其中任何一个都可以完成最后一个.您观察到的序列完全是随机的,可能会不时出现.
"这是由于多个线程同时尝试访问共享资源."这在上下文中实际上是无关紧要的,因为它们之间实际上没有共享资源.