类型不匹配:无法从 void 转换为 Thread

Type mismatch: cannot convert from void to Thread

我正在尝试在 java 中制作一个接受任何连接的程序,但出现此错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from void to Thread

at ojas.gome.Server.<init>(Server.java:37)
at ojas.gome.Server.main(Server.java:12)

这段代码给我这个错误:

clientaccepter = new Thread(new Runnable() {
            public void run() {
                while(true) {
                    try {
                        server.accept();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "clientaccepter").run();

如果我遗漏了任何需要的东西,请告诉我。

您设置的变量等于 run 方法的结果,它不是 return 值 - 它是 void

clientaccepter = new Thread....run();

如果需要保留对线程的引用,则应声明该线程,然后在单独的行中启动它。此外,您应该使用 start 开始新的 Thread 而不是 run。请参阅 Defining and Starting a Thread. Lastly, variables should be camel case starting with lowercase - please see Java Naming Conventions

clientAccepter = new Thread(...);
clientAccepter.start();
  1. 要么去完成语句 Thread t = new Thread( new Runnable () ) 并调用 t.run() 或
  2. 在调用 start() 时直接创建 new Thread() (new Runnalbe()) 如下:

    public class InterfaceDemo {
    
        public static void main(String[] args) {
    
         new Thread(new Runnable() 
        {
            @Override
            public void run() 
            {
                for(int i=0;i<=10;i++) {
                    System.out.println("run() : "+i);
                }
            }
        }).start();
    
            for(int i = 1; i<=10; i++) {
                System.out.println("main() : "+i);
            }
        }// main
    } // class