当我尝试多次执行以下多线程代码时,输出与前一个不同。是因为 JVM 行为还是可能是其他原因。请帮我一个。
program:
package example.thread.com;
class MyThread1 implements Runnable {
Thread t;
MyThread1(String s) {
t = new Thread(this, s);
t.start();
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread Name :"
+ Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
}
}
public class RunnableThread1 {
public static void main(String args[]) {
System.out.println("Thread Name :" + Thread.currentThread().getName());
MyThread1 m1 = new MyThread1("My Thread 1");
MyThread1 m2 = new MyThread1("My Thread 2");
}
}
输出:如果我第一次运行
Thread Name :main
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
输出:如果我第二次运行
Thread Name :main
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
输出:如果我第三次运行
Thread Name :main
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
像这样请建议.....