执行程序没有运行所有的线程。(Executors are not running all the threads.)
我是Java新手,我正在尝试这个。 我有方法,我希望并行运行该方法。 我希望应该有10个线程调用该方法并获得结果。
我正在使用
Callable
和Executors
。 我正在创建线程池: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
andExecutors
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
最满意答案
就像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.
相关问答
更多-
cookie := http.Cookie{Name: "_c_id_", Value: "abcd", Path: "/", HttpOnly: true, Secure: false} server := websocket.Server{Handler: websocket.Handler(EchoServer)} server.Config.Header = make(map[string][]string) server.Config.Header.Set("Set-Cookie", cooki ...
-
就像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{ ...
-
Apollo 2.x客户端和服务器设置:WebSocket握手期间出错?(Apollo 2.x Client and Server Setup: Error during WebSocket handshake?)[2023-06-12]
首先想到的是: 您的服务器侦听端口3200并使用路由graphql 。 const subscriptionServer = SubscriptionServer.create( { schema, execute, subscribe, }, { server: websocketServer, path: '/graphql', // used url route }, ) ... -
在go.crypto/ssh包的源代码中,我们可以看到支持的密码如下: AES128-CTR AES192-CTR AES256-CTR arcfour128 arcfour256 虽然freeSSHd支持: AES128-CBC AES192-CBC AES256-CBC 3DES-CBC 河豚-CBC rijndael128-CBC rijndael192-CBC rijndael256-CBC rijndael-cbc@lysator.liu.se 由于客户端和服务器不共享密码,因此您将收到错误消息。 ...
-
静态html页面直接创建了WebSocket连接golang服务器(Static html page created the WebSocket connection golang server directly)[2021-12-10]
Chrome可能会抛出400错误,因为它认为您正在尝试向websocket服务器执行跨域请求,并认为您不太可能获得权限。 要解决这个问题,你只需要从你的go -server服务你的html。 所以将你的sock.go代码更改为: package main import ( "code.google.com/p/go.net/websocket" "fmt" "log" "net/http" ) func Echo(ws *websocket.Conn) { var ... -
服务器违反了WebSocket协议。 Chrome很可能在版本20中更加正确地遵守该标准,并且揭示了服务器中的错误。 问题在于服务器在响应中发回“Sec-WebSocket-Protocol”头,但这只有在客户端在请求中发送相同头时才合法。 如果客户端没有发送Sec-WebSocket协议,那么服务器应该在响应中省略标题。 请参阅rfc6455第4.2.2节中的第22页上的/ subprotocol / description The server is violating the WebSocket pr ...
-
regexp /Sec-WebSocket-Key:\s*(.*)\s*/将包含匹配内容中的\r \n字符( .匹配\r \n但不是\n ),因此您的$key变量将出错值。 你需要找出一个正则表达式,它匹配除了末尾的\r\n序列之外的所有内容。 此外,如果客户端将其包含在请求中,则服务器应仅包含Sec-WebSocket-Protocol属性,并且该值必须是客户端Sec-WebSocket-Protocol属性中请求的协议之一。 否则客户端将给出错误,请参阅RFC 6455 。 The regexp /Se ...
-
Tyrus抱怨Connection: keep-alive, Upgrade header。 Firefox在这里没有做错任何事。 关于如何处理Connection标头,Tyrus过于严格,没有遵循WebSocket规范( RFC-6455 )。 RFC 4.1中的RFC规定: 6. The request MUST contain a |Connection| header field whose value MUST include the "Upgrade" token. ...
-
我得到了这个查询的答案。 这是因为添加的jar会覆盖apache tomcat中的内部jar。 我正在使用没有websocket-api.jar的旧tomcat 所以我对这个问题的解决方案是使用glashfish 4.x或者使用apache tomcat 8.x,它给我们提供了运行websocket所需的jar。 不需要添加任何额外的websocket api jar。 I got answer for this query. This is because the added jar overrides ...
-
你不应该用钥匙回答吗? 尝试在响应中添加Sec-WebSocket-Accept:sha1(Sec-WebSocket-Key +魔术字符串) shouldn't you respond with the key? try to add Sec-WebSocket-Accept: sha1(Sec-WebSocket-Key + magic string ) on your response