java一创建线程就开始执行(多线程)
class Mythread implements Runnable {
Thread thrd;
Mythread(String name){
thrd = new Thread(this, name) ;
}
public static Mythread createAndStart(String name) {
Mythread mythrd = new Mythread(name) ;
mythrd.thrd.start() ;
return mythrd ;
}
public void run() {
System.out.println(thrd.getName()+ " Starting.") ;
try {
for(int i = 0 ; i < 10 ; i++) {
Thread.sleep(400);
System.out.println("In "+ thrd.getName() +", count is "+i) ;
}
}
catch(Exception E) {
}
System.out.print(thrd.getName()+" terminating.") ;
}
}
public class demo{
public static void main(String[] args) {
System.out.println("Main thread Starting") ;
Mythread mt = Mythread.createAndStart("child #1") ;
for(int i = 0 ; i < 50 ; i++) {
System.out.print(".") ;
try {
Thread.sleep(100);
}
catch(Exception e) {
}
}
System.out.println("Main thread Ending") ;
}
}
在上面的代码中,我们为什么不能编写thrd。开始()而不是mythrd。第三。开始()。这是什么意思?还有,为什么我们要用同样的方法返回mythrd对象? 既然CreateAndStart方法在main方法中返回对mt的mythrd引用,那么mt有什么用呢
共 (0) 个答案