java为什么实现runnable总是交织结果?
离开我最后一个关于线程的问题, Why my input is showing one thread executing after another thread, not at the same time?, 我得到的回答是:“在多线程的情况下,无法保证哪个线程被分配给处理器运行的时间,在这种情况下,结果是不可预测的,每次运行都会产生不同的输出。”
然而,当我用另一种方法(实现可运行)测试结果不可预测的想法时,结果总是交织在一起的,而且是一样的。与扩展线程相比,有人能解释这种一致性吗? 可运行的实现代码
class Runner implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i =0; i< 10; i++){
System.out.println("Hello " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class App {
public static void main(String[] args){
Thread t1 = new Thread(new Runner());
Thread t2 = new Thread(new Runner());
t1.start();
t2.start();
}
}
和输出(一致):http://imgur.com/rhDVUhD
# 1 楼答案
正如多个评论者已经指出的那样,很有可能你的代码已经开始相互交织。我已经在我的工作站上测试过了,线程的执行顺序是不可预测的
根据你的用户名,我希望你能参加Coursera课程"Programming Mobile Services for Android Handheld Systems"
它包括关于多线程的多种模式和示例。比如这个错误实现的乒乓球应用程序,它会产生你想要的效果:PingPongWrong.java