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

时间:2017-11-21 03:38:41

标签: java multithreading server connection

我试图在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();

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

2 个答案:

答案 0 :(得分:1)

您设置的变量等于run方法的结果,该方法没有返回值 - 它是void

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

如果需要保留对它的引用,则应该声明该线程,然后在单独的行上启动它。此外,您应该使用start开始新的Thread而不是run。请参阅Defining and Starting a Thread。最后,变量应该是以小写字母开头的驼峰式案例 - 请参阅Java Naming Conventions

clientAccepter = new Thread(...);
clientAccepter.start();

答案 1 :(得分:0)

  1. 要么去完整语句线程t =新线程(new Runnable()) 并调用t.run()或
  2. 在该调用start()上直接创建新的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
    
相关问题