首页 \ 问答 \ 执行程序没有运行所有的线程。(Executors are not running all the threads.)

执行程序没有运行所有的线程。(Executors are not running all the threads.)

我是Java新手,我正在尝试这个。 我有方法,我希望并行运行该方法。 我希望应该有10个线程调用该方法并获得结果。

我正在使用CallableExecutors 。 我正在创建线程池:

 ExecutorService executor = Executors.newFixedThreadPool(10);

当我这样做时:

 executor.invokeAll(taskList);

在10个线程中,只有1个线程被从轮询中取出。 我只得到这印:

The current thread is pool-1-thread-1

但我希望应该有10个类似的println声明。

以下是完整的代码:

import java.util.concurrent.Callable;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;

public class Parallel
{
    public static void main(String args[])
    {
        Learning l = new Learning();
        l.message = "1st Object";
        l.testThread();
    }
}

//this class deals with threads
class Learning
{

    public String message;

    public void setMessage(String message)
    {
        this.message = message;
    }

    //contains the code where
    public void testThread()
    {

       //create a callable for each method
       Callable<String> callable1 = new Callable<String>()
       {
          @Override
          public String call() throws Exception
          {
             System.out.println("The current thread is " + Thread.currentThread().getName());
             return method1();
             // return null;
          }
       };


       //add to a list
       List<Callable<String>> taskList = new ArrayList<Callable<String>>();
       taskList.add(callable1);

       //create a pool executor with 10 threads
       ExecutorService executor = Executors.newFixedThreadPool(10);


       try
       {
         List<Future<String>> futureList = executor.invokeAll(taskList);

       }
       catch (InterruptedException ie)
       {
       }
    }

    //put your code here!
    private String method1()
    {
        return Thread.currentThread().getName();
    }
}

我在这里错过了什么吗?


I'm new to Java, and I'm trying this. I have method, which I wish to run that method in parallel. I wish there should be 10 threads calling the method and get their results.

I'm using Callable and Executors for that. I'm creating the thread pool as:

 ExecutorService executor = Executors.newFixedThreadPool(10);

and I when I do this:

 executor.invokeAll(taskList);

out of 10 threads, only 1 thread is been taken from the poll. And I get only this printed:

The current thread is pool-1-thread-1

But I wish there should be 10 similar println statements.

Here is the full code:

import java.util.concurrent.Callable;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;

public class Parallel
{
    public static void main(String args[])
    {
        Learning l = new Learning();
        l.message = "1st Object";
        l.testThread();
    }
}

//this class deals with threads
class Learning
{

    public String message;

    public void setMessage(String message)
    {
        this.message = message;
    }

    //contains the code where
    public void testThread()
    {

       //create a callable for each method
       Callable<String> callable1 = new Callable<String>()
       {
          @Override
          public String call() throws Exception
          {
             System.out.println("The current thread is " + Thread.currentThread().getName());
             return method1();
             // return null;
          }
       };


       //add to a list
       List<Callable<String>> taskList = new ArrayList<Callable<String>>();
       taskList.add(callable1);

       //create a pool executor with 10 threads
       ExecutorService executor = Executors.newFixedThreadPool(10);


       try
       {
         List<Future<String>> futureList = executor.invokeAll(taskList);

       }
       catch (InterruptedException ie)
       {
       }
    }

    //put your code here!
    private String method1()
    {
        return Thread.currentThread().getName();
    }
}

Am I missing something here?


原文:https://stackoverflow.com/questions/20416223
更新时间:2023-06-12 20:06

最满意答案

就像JimB指出的那样,你还没有处理http和websocket连接。

您可以使用github.com/gorilla/websocket包进行websocket处理这是一个简单的设置如下所示:

package main

import (    
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

// wsHandler implements the Handler Interface
type wsHandler struct{}

func main() {
    router := http.NewServeMux()
    router.Handle("/", http.FileServer(http.Dir("./webroot"))) //handles static html / css etc. under ./webroot
    router.Handle("/ws", wsHandler{}) //handels websocket connections

    //serving
    log.Fatal(http.ListenAndServe("localhost:8080", router))
}

func (wsh wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // upgrader is needed to upgrade the HTTP Connection to a websocket Connection
        upgrader := &websocket.Upgrader{
            ReadBufferSize:  1024,
            WriteBufferSize: 1024,
        }

        //Upgrading HTTP Connection to websocket connection
        wsConn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Printf("error upgrading %s", err)
            return
        }

        //handle your websockets with wsConn
}

在你的Javascript中你需要var sock = new WebSocket("ws://localhost/ws:8080"); 明显。


Like JimB pointed out, you are not handling http nor websocket connections yet.

You can do websocket handling with the package github.com/gorilla/websocket This is how a simple setup could look like:

package main

import (    
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

// wsHandler implements the Handler Interface
type wsHandler struct{}

func main() {
    router := http.NewServeMux()
    router.Handle("/", http.FileServer(http.Dir("./webroot"))) //handles static html / css etc. under ./webroot
    router.Handle("/ws", wsHandler{}) //handels websocket connections

    //serving
    log.Fatal(http.ListenAndServe("localhost:8080", router))
}

func (wsh wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // upgrader is needed to upgrade the HTTP Connection to a websocket Connection
        upgrader := &websocket.Upgrader{
            ReadBufferSize:  1024,
            WriteBufferSize: 1024,
        }

        //Upgrading HTTP Connection to websocket connection
        wsConn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Printf("error upgrading %s", err)
            return
        }

        //handle your websockets with wsConn
}

In your Javascript you then need var sock = new WebSocket("ws://localhost/ws:8080"); obviously.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)