【发布时间】:2016-11-13 17:34:49
【问题描述】:
我正在尝试线程优先级的影响,当运行方法中的 println 停留在注释中时,两个线程同时结束,我不明白这种行为,你能解释一下吗?谢谢。
主类
public class Main {
public static void main(String[] args) {
Test t1 = new Test("Thread #1");
Test t2 = new Test("Thread #2");
t1.thread.setPriority(10);
t2.thread.setPriority(1);
t1.thread.start();
t2.thread.start();
try {
t1.thread.join();
t2.thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t1.thread.getName() + ": " + t1.count);
System.out.println(t2.thread.getName() + ": " + t2.count);
System.out.println("End of main thread.");
}
}
Test.class
public class Test implements Runnable{
public Thread thread;
static boolean stop = false;
int count = 0;
public Test(String name){
thread = new Thread(this, name);
}
@Override
public void run(){
for(int i = 0; i < 10000000 && stop == false; i++){
count = i;
//System.out.println(count + " " + thread.getName());
}
stop = true;
System.out.println("End of " + thread.getName());
}
}
without println with println End of Thread #1 End of Thread #1 End of Thread #2 End of Thread #2 Thread #1: 9999999 Thread #1: 9999999 Thread #2: 9999999 Thread #2: 3265646 End of main thread. End of main thread.
【问题讨论】:
-
您期望什么行为?你的电脑有几个核心?你认为线程优先级是多少?
-
“两个线程同时结束”是什么意思?您对这种行为有什么不理解的地方?
-
您的输出描述了正确的行为。您还有什么期望?
-
我不知道为什么没有 print 它们会同时结束,而当我将 print 与 counter 一起循环时它们不会。我的电脑有 2 核 / 4 线程。
标签: java multithreading java-8