在阅读线程时我遇到了以下代码
Runnable r = new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
int count = 0;
while (!Thread.interrupted())
System.out.println(name + ": " + count++);
}
};
Thread thdA = new Thread(r);
Thread thdB = new Thread(r);
thdA.start();
thdB.start();
while (true) {
double n = Math.random();
if (n >= 0.49999999 && n <= 0.50000001)
break;
}
thdA.interrupt();
thdB.interrupt();
并且这段代码运行顺利但是当我试图将这段代码划分为方法时,它没有显示任何输出,我做错了吗?
public String runableStatements() {
String name = Thread.currentThread().getName();
int count = 0;
while (!Thread.interrupted()) {
System.out.println(name + " : " + count++);
}
return name + String.valueOf(count);
}
public Runnable runnableTarget(ThreadInteruptionDemo demo) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
demo.runableStatements();
}
};
return r;
}
public void startThreads(ThreadInteruptionDemo demo) {
Thread thOne = new Thread(demo.runnableTarget(demo));
Thread thTwo = new Thread(demo.runnableTarget(demo));
thOne.start();
thTwo.start();
while (true) {
double n = Math.random();
if (n >= 0.49999999 && n <= 0.500000001) {
System.out.println(n);
break;
}
thOne.interrupt();
thTwo.interrupt();
}
}
public static void main(String[] args) {
// ThreadInteruptionDemo demo = new ThreadInteruptionDemo();
// demo.startThreads(demo);
输出第一个代码
Thread-0: 86470
Thread-0: 86471
Thread-0: 86472
Thread-0: 86473
Thread-0: 86474
Thread-0: 86475
Thread-0: 86476
Thread-0: 86477
Thread-0: 86478
Thread-0: 86479
而第二个输出是
主题-0 线程1
我错过了什么,我做错了什么? 如果是,那么如何解决这个问题?
编辑在调试第二个代码时,它没有显示任何输出