当我跑步时:
class ThreadOne extends Thread {
ThreadOne(String name) {
super(name);
start();
}
public void run() {
try {
sleep(1);
} catch (InterruptedException ie) {
}
}
public static void main(String args[]) throws InterruptedException {
ThreadOne n1 = new ThreadOne("Thread 1");
int counter = 0;
while (true) {
if (n1.isAlive() == true) {
counter++;
System.out.println("Thread 1 still running. Counter: " + counter);
} else {
System.out.println("Thread 1 executed");
break;
}
}
}
}
我得到的结果如下:
Thread 1 still running. Counter: 1
Thread 1 still running. Counter: 2
...
Thread 1 still running. Counter: 40
Thread 1 still running. Counter: 41
Thread 1 executed
但是当我在sleep()中更改参数时,计数器会急剧增加。这是我放睡眠的例子(5):
Thread 1 still running. Counter: 1
Thread 1 still running. Counter: 2
...
Thread 1 still running. Counter: 154
Thread 1 still running. Counter: 155
Thread 1 executed
是什么让这个线程停止执行,为什么sleep()
会影响计数器?