黑马程序员技术交流社区
标题:
多线程中通过实现Runnable接口创建一个新的线程中的问题
[打印本页]
作者:
李贺晓
时间:
2012-9-25 14:36
标题:
多线程中通过实现Runnable接口创建一个新的线程中的问题
本帖最后由 李贺晓 于 2012-9-25 15:09 编辑
class NewThread implements Runnable {
Thread t;
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); }
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
通过实现Runnable接口创建了一个新的线程,并启动他
在新的的构造函数NewThread中为什么要用到t,在构造函数前面声明Thread t,这里主要是起什么作用的?期待回答
作者:
李贺晓
时间:
2012-9-25 14:47
补充一下,在这个创建多个线程的程序中
class NewThread implements Runnable {
String name;
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
对这里的使用isAlive()和join()方法时,创建的线程对象的名字为obj1,obj2,obj3,调用的时候为什么回事obj1.t.join()和obj1.t.isAlive()呢
在这里前面的构造函数前面定义Thread t中的t主要起到什么作用呢?
作者:
孙岳
时间:
2012-9-25 14:48
本帖最后由 孙岳 于 2012-9-25 14:51 编辑
实现Runnable接口是为了重写run方法,并不能创建新的线程。
创建新线程是
Thread t;
t = new Thread();
相当于
Thread t = new Thread();
这个构造方法的目的在于用构造方法创建对象的时候就直接创建了一个线程,并且启动。
之所以把t定义在构造方法的外面,是因为这样t就成了类的属性,可以通过对象调用t来操作构造方法内创建的线程。
比如
NewThread nt = new NewThread();
nt.t.dosomething;
补充:
这个nt.t.dosomething可以解释你补充的问题。
作者:
汪小照
时间:
2012-9-25 14:50
你NewThread实现Runnable接口后,重写run方法,但此类中并且没有strat方法,而线程是通过start方法启动的,strat方法启动后,它就会自动调用run方法,所以你需要创建NewThread对象,创建Thread对象,也就是你程序中的t对象,再把NewThread对象传给t对象,这时t对象就可以使用的自己的start方法来调用传进来的对象中的run方法了。
所以t的作用可以用一句简而言之的概括:就是用自己的start方法来启动重写的run方法。
作者:
李贺晓
时间:
2012-9-25 15:03
孙岳 发表于 2012-9-25 14:48
实现Runnable接口是为了重写run方法,并不能创建新的线程。
创建新线程是
Thread t;
嗯,明白啦,介绍的很详细
作者:
李贺晓
时间:
2012-9-25 15:10
问题已解决
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2