我一直试图找出以下Java程序输出背后的原因:
public class Main {
public static void main(String args[]) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Implementation");
}
};
MyThread gaurav = new MyThread(r);
new Thread(r).start();
gaurav.start();
}
}
class MyThread extends Thread {
Runnable runnable;
public MyThread(Runnable r) {
runnable = r;
}
@Override
public void run() {
super.run();
System.out.println("Thread");
}
}
以上输出是:'实施'其次是'线程'在下一行。现在问题在于这个陈述:
gaurav.start();
当我将runnable r传递给MyThread时,我认为r会被执行,因此,输出将是' Implementation'也是这样。但显然,我错过了一些东西。这些陈述之间也有区别:
new Thread(r).start();
gaurav.start();
对于这种情况非常有用。感谢。
答案 0 :(得分:1)
请考虑以下事项:
public class Main {
public static void main(String args[]) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Implementation");
}
};
MyThread gaurav = new MyThread(r);
gaurav.start();
}
}
class MyThread extends Thread {
Runnable runnable;
public MyThread(Runnable r) {
// calling Thread(Runnable r) constructor.
super(r);
// runnable isn't used anywhere. You can omit the following line.
runnable = r;
}
@Override
public void run() {
// First it will run whatever Runnable is given
// into Thread's constructor.
super.run();
System.out.println("Thread");
}
}
输出:
Implementation
Thread
我猜您的混淆来自Runnable
中的MyThread
字段。你认为通过它在那里,你以某种方式覆盖Thread
自己的可运行但你没有。如果你想这样做,你应该在你的构造函数中调用super(r)
。
答案 1 :(得分:0)
MyThread的start方法将启动线程的run方法,其中System.out.println("Thread");
new Thread(r).start();
将运行System.out.println("Implementation");
它完全依赖于操作系统的调度程序,首先运行哪个线程。所以你可能会看到输出为:
Implementation
Thread
或者
Thread
Implementation