这段代码工作正常,但如果我在第 6 行使用构造函数 Thread(name) 而不是 Thread(this,name) 它不起作用我只想知道是什么造成了差异?
public class threadtest implements Runnable{
Thread t;
public threadtest(String name)
{
System.out.println("satheesh");
Thread t=new Thread(this,name);
t.start();
t=null;
//System.out.println(this+"\n"+t);
}
public void run(){
System.out.println("satheesh");
for(int i=0;i<=10;i++)
{
try{
System.out.println("satheesh");
Thread.sleep(1000);
System.out.print(Thread.currentThread());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String args[])
{
threadtest ob=new threadtest("satheesh");
}
}
最佳答案
创建线程有两种方式:
子类
Thread
,覆盖run
,然后创建子类的实例扩展
Runnable
并将其交给一个线程来“运行”它
您的代码执行 #2 - 您实现了 Runnable
,因此您必须将它交给一个线程来“运行”它。
if I use the constructor
Thread(name)
in 6th line instead ofThread(this,name)
it is not working I just want to know what makes the difference?
区别在于:
Thread t= new Thread(this,name);
创建一个新线程,在启动时为您的
Runnable
(this
) 运行。Thread t= new Thread(name);
创建一个新线程不给定任何
Runnable
运行。所以线程在启动时什么都不做。
关于java - 使用 Runnable 和 Thread 创建线程的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4806350/