我制作了一个使用线程的程序---
public class ThreadTest{
public static void main(String[] args){
MyThread newthread=new MyThread();
Thread t=new Thread(newthread);
t.start();
for(int x=0;x<10; x++){
System.out.println("Main"+x)
}
}
}
Run Code Online (Sandbox Code Playgroud)
class MyThread implements Runnable{
public void run(){
for(int x=0; x<10; x++){
System.out.println("Thread"+x);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是......为什么我们使用"Thread"类并创建它的对象并在其构造函数中传递"MyThread"调用?我们不能通过创建它的对象并调用run方法来调用"MyThread"对象的run方法吗?
(即 MyThread newthread=new MyThread(); and then newthread.run(); )
创建胎面对象并在其中传递MyThread类的原因是什么?
Mar*_*ers 10
这个MyThread类不是一个线程.它是一个普通的类,它实现Runnable并有一个名为的方法run.
如果run直接调用该方法,它将在当前线程上运行代码,而不是在新线程上运行.
要启动一个新线程,您需要创建一个新的而不是Thread类,给它一个实现的对象,Runnable然后start在线程对象上调用该方法.线程启动时,它会run为您调用对象上的方法.
启动线程的另一种方法是子类化Thread并覆盖其run方法.再次启动它你必须实例化它并调用start方法,而不是run方法.原因是相同的:如果你run直接调用它将在当前线程中运行该方法.
有关在Java中启动新线程的更多信息,请参阅定义和启动线程.