public class CreateThreadRunnableExample implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Child Thread : " + i);
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Child thread finished!");
}
public static void main(String[] args) {
Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");
t.start();
for (int i = 0; i < 5; i++) {
System.out.println("Main thread : " + i);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Main thread finished!");
}
}在这个程序中,使用了两种不同时间的休眠方法,所以如果主线程运行时,子线程必须运行2次,那么为什么只有一个子线程运行一次。当主线程结束时,我们采用time.but或state....then的概念,当主线程结束时,两个子线程将处于就绪状态,那么为什么只有一个子线程运行。
发布于 2012-05-22 15:12:04
正如JavaDoc中所述,sleep方法并不是100%准确的时间
公共静态无效睡眠(Long millis)抛出InterruptedException
使当前执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和计划程序的精确度。该线程不会丢失任何监视器的所有权。
因此,代码有时可能会按预期工作,而有时则不会。
而且,你似乎只有一个孩子,那么为什么你还想要两个孩子呢?
编辑:理论上是这样的,在main线程休眠时,子线程应该执行两次。也就是说,正如在JavaDoc中所解释的那样,sleep方法执行的准确性取决于它所运行的系统,因此有时您可能会让它按预期工作,而在另一些时候则不是。例如,您可能会遇到这样的场景:main线程休眠97毫秒,而不是100毫秒,而子线程休眠53毫秒。这将导致该子进程仅执行一次。
另一种选择是这样做:while (currentTime <= timeNeededToElapse) { currentTime=... }。这导致了一个紧凑的while循环,它可以提供更好的控制,但据我所知,它仍然不是100%准确的,更不用说你会因为实际上什么都不做而消耗CPU周期,所以要谨慎使用。
发布于 2012-05-22 15:27:31
首先,您添加了System.out.println(“子线程中断!”+ ie);对于主线程和子线程,这都是一个拼写错误……
试试这个。两个线程都在运行(主线程和子线程)
该程序的Main方法被放在由JVM创建的主线程的底部,Main方法创建另一个运行时堆栈,并将子线程放入其中。
public class DemoThread implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Child Thread ");
try {
Thread.sleep(200);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Child thread finished!");
}
public static void main(String[] args) {
Thread t = new Thread(new DemoThread ());
t.start();
for (int i = 0; i < 3; i++) {
System.out.println("Main thread);
try {
Thread.sleep(200);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Main thread finished!");
}
}发布于 2012-05-22 15:08:32
您只启动了一个子线程,为什么还期望启动两个子线程?
关于超时,睡眠时间是不准确的,所以当一个线程睡眠100ms时,另一个线程可能会睡眠两次,也可能不会睡眠50ms。这是一个经典的示例。如果您多次运行示例代码,在某些情况下可能会看到两个子线程消息,而在其他情况下可能会看到一个。
https://stackoverflow.com/questions/10697311
复制相似问题