你什么时候打电话给Java thread.run()而不是thread.start()?
请解释以下代码的输出:
如果我打电话th1.run(),输出是:
EXTENDS RUN>>
RUNNABLE RUN>>
Run Code Online (Sandbox Code Playgroud)
如果我打电话th1.start(),输出是:
RUNNABLE RUN>>
EXTENDS RUN>>
Run Code Online (Sandbox Code Playgroud)
为什么这种不一致?请解释.
class ThreadExample extends Thread{
public void run() {
System.out.println("EXTENDS RUN>>");
}
}
class ThreadExampleRunnable implements Runnable {
public void run() {
System.out.println("RUNNABLE RUN>>");
}
}
class ThreadExampleMain{
public static void main(String[] args) {
ThreadExample th1 = new ThreadExample();
//th1.start();
th1.run();
ThreadExampleRunnable th2 = new ThreadExampleRunnable();
th2.run();
}
}
Run Code Online (Sandbox Code Playgroud) 我制作了一个使用线程的程序---
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类的原因是什么?