读书人

线程有关问题:3有关问题

发布时间: 2013-08-09 15:16:24 作者: rapoo

线程问题: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
{


Thread.sleep(300);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}

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


[解决办法]
"why : x is 51
y is 13"
你输入“3”,回车后跟着回车和换行符。“3”的ascii码是 51(10进制),回车的的ascii码是 13(10进制),换行的ascii码是10。因为只输出2个,所以这个换行没有输出。

[解决办法]
问题2 关键理解Thread 类(包括继承的类),和实现了Runnable接口的类是不一样的。

class ChildThread implements Runnable {
Thread childThread;

ChildThread() {

childThread = new Thread(this, "Child Thread");
//childThread = new Thread();
System.out.println("Child thread: " + childThread);//这个childThread是Thread类的对象引用。
System.out.println("Child thread: " + this);//这个this 是这个实现了Ruunable接口的类ChildThread对象的引用。
childThread.start();
}

[解决办法]
引用:
[quot ]
问题2 关键理解Thread 类(包括继承的类),和实现了Runnable接口的类是不一样的。


extends Thread,implements Runnable 各在什么情况下用?

super,this 我也不熟


extends Thread,implements Runnable 这个都可以的,只是因为java是单继承,如果用了extends Thread就不能继承其他的类了,所以一般用实现接口的方式更多。

读书人网 >J2SE开发

热点推荐