相关疑难解决方法(0)

108
推荐指数
9
解决办法
7万
查看次数

请解释Thread run()和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)

java multithreading

9
推荐指数
1
解决办法
6909
查看次数

为什么我们需要调用thread.start()而不是thread.run()?

可能重复:
java thread - run()和start()方法

我制作了一个使用线程的程序---

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类的原因是什么?

java

2
推荐指数
1
解决办法
1376
查看次数

标签 统计

java ×3

multithreading ×2

concurrency ×1