日期:2014-05-20  浏览次数:20762 次

线程问题:3问题
问题1: 哪种方式好?


<1>

           
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(150);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}

=============================================================================
  <2>

for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
try {
Thread.sleep(150);
} catch (InterruptedException e) {
 
e.printStackTrace();
}
}


------解决方案--------------------
Quote: 引用:

问题3:为什么不在***处等待键盘输入?



public class DaemonDemo1 extends Thread {

public void run() {
 
 
System.out.println("in child");
System.in.read();  // <----------***
}

public static void main(String[] args) {
DaemonDemo1 test = new DaemonDemo1();
// test.setDaemon(true);
test.start();
 Thread.sleep(300);

System.out.println("in main");
System.in.read(); 

}

}


结果是:
in child
in main

( 忽略异常处理

程序是等待键盘输入呢。可以加点代码试一下:

import java.io.IOException;

public class DaemonDemo1 extends Thread {

public void run() {

System.out.println("in child");
try {
System.out.println("wait in run ");
int x = System.in.read(); // <----------***
System.out.println("x is "+x);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

public static void main(String[] args) {
DaemonDemo1 test = new DaemonDemo1();
// test.setDaemon(true);
test.start();
try
{