Java 无法在eclipse中使用main方法执行类扩展线程
无法在eclipse中执行此操作。有什么特别的原因吗?在启用execute选项之前,eclipse是否查找任何特定的内容? 如果执行下面的代码,结果会是什么?是“1”吗Java 无法在eclipse中使用main方法执行类扩展线程,java,eclipse,multithreading,Java,Eclipse,Multithreading,无法在eclipse中执行此操作。有什么特别的原因吗?在启用execute选项之前,eclipse是否查找任何特定的内容? 如果执行下面的代码,结果会是什么?是“1”吗 编辑:只是玩继承和线程。这里没有测试特定的线程功能。您只需将类设置为公共 public class A extends Thread { private int i; public void run(){i=1;} public static void main(String[] args) {
编辑:只是玩继承和线程。这里没有测试特定的线程功能。您只需将类设置为公共
public class A extends Thread {
private int i;
public void run(){i=1;}
public static void main(String[] args) {
A a = new A(); a.run();System.out.println(a.i);
}
}
@侯赛因把你们的课公之于众是对的,但我想我应该为后代补充一些额外的信息
- 正如您的代码现在所示,您并没有在另一个线程中运行代码。您可以从代码中删除
,它仍然可以正常工作。您的扩展线程
只是直接调用main
方法,而没有调用任何线程魔法run()
- 如果确实希望代码在另一个线程中运行,则需要添加
启动线程运行并a.start()
a.join()代码>等待它完成。在
方法中,线程被分叉并调用start()
方法run()
A a = new A(); // start the thread which calls run() a.start(); // wait for the thread to finish a.join(); System.out.println(a.i);
- 最后,建议您
并执行与实现Runnable
扩展线程相反的操作。因此,您的代码如下所示:
A a = new A(); Thread thread = new Thread(a); // start the thread which calls run() thread.start(); // wait for the thread to finish thread.join(); System.out.println(a.i);
- 如果你以前没有这样做过,我建议你读一本书
A a = new A();
Thread thread = new Thread(a);
// start the thread which calls run()
thread.start();
// wait for the thread to finish
thread.join();
System.out.println(a.i);