Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-如何使用Executor服务同时运行两个静态函数和void函数_Java_Multithreading_Networking - Fatal编程技术网

Java-如何使用Executor服务同时运行两个静态函数和void函数

Java-如何使用Executor服务同时运行两个静态函数和void函数,java,multithreading,networking,Java,Multithreading,Networking,我正试图让我的程序准备好发送一条用户输入的消息,同时监听传入的消息 我尝试使用Executor服务,但它总是给出一个错误,说明函数不能是静态的或无效的 正因为如此,我尝试使我的两个函数(我需要同时运行)成为非静态的,并返回一个我不会使用的字符串。不幸的是,我仍然得到一个错误,我认为这是因为我的函数使用了前面声明的静态类变量 下面是我得到的错误: java:66:错误:不是抽象的 并且不会覆盖Callable中的抽象方法调用() add(newcallable()){ 以下是简化的代码,没有Exe

我正试图让我的程序准备好发送一条用户输入的消息,同时监听传入的消息

我尝试使用Executor服务,但它总是给出一个错误,说明函数不能是静态的或无效的

正因为如此,我尝试使我的两个函数(我需要同时运行)成为非静态的,并返回一个我不会使用的字符串。不幸的是,我仍然得到一个错误,我认为这是因为我的函数使用了前面声明的静态类变量

下面是我得到的错误:

java:66:错误:不是抽象的 并且不会覆盖Callable中的抽象方法调用() add(newcallable()){

以下是简化的代码,没有Executor服务:

class EchoClient
{   
    public static DatagramSocket socket; public static InetAddress receiver; public static int port;
    
    public static void main( String args[] ) throws Exception
    {
        //Initialization of socket, receiver and port
        
        while(true)
        {
            sendMessage();
            receiveMessage();
        }
        
    }

    public static void sendMessage() throws IOException
    {
        //Actions to send message
    }
    
    public static void receiveMessage() throws IOException
    {
        //Actions to receive message
    }
    
}
我想同时运行的函数是
sendmages()
receiveMessage()
。现在我使用的是while循环,因此程序只能在等待接收消息之前发送消息,反之亦然


我真的不太熟悉Java,所以我只希望Executor服务的简单实现。

因为您知道需要两个线程,所以可以使用FixedThreadPool:

Executor executor = Executors.newFixedThreadPool(numberOfThreads);
要执行任务,只需使用runnable作为参数调用execute方法:

executor.execute(() -> {
    while (true) {
        try {
            sendMessage();
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }
});