Java 无法在eclipse中使用main方法执行类扩展线程

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) {

无法在eclipse中执行此操作。有什么特别的原因吗?在启用execute选项之前,eclipse是否查找任何特定的内容? 如果执行下面的代码,结果会是什么?是“1”吗


编辑:只是玩继承和线程。这里没有测试特定的线程功能。

您只需将类设置为公共

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);
    
  • 如果你以前没有这样做过,我建议你读一本书


错误消息是什么?(顺便说一句,它在这里运行良好:)。我无法在“运行方式”菜单中看到“Java应用程序”。请设置您的类public@HussainAkhtarWahid非常感谢。明白了:)解释得很好。谢谢格雷。再次感谢侯赛因:)
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);