Java 同时运行2个线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/768966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:16:02  来源:igfitidea点击:

Running 2 threads simultaneously

javamultithreadingnetwork-programmingsimultaneous-calls

提问by lamsaitat

In the case of an IM client. I have made 2 separate threads to handle sending packets (by std io) and receiving packets. The question is how to make these 2 threads run simultaneously so that I can keep prompting for input while at the same time be ready to receive packets at any time?

在 IM 客户端的情况下。我制作了 2 个单独的线程来处理发送数据包(通过 std io)和接收数据包。问题是如何让这两个线程同时运行,以便我可以不断提示输入,同时随时准备接收数据包?

I have already tried setting a timer but the data is always lost receiving.

我已经尝试设置一个计时器,但数据总是丢失接收。

采纳答案by KarlP

I think you might have missed something significant with either Threads, Streams or both :-)

我认为您可能错过了线程、流或两者的重要内容:-)

You can start a new thread like this:

您可以像这样开始一个新线程:

myThread.start();

The thread will be started and the run() method will be executed automatically by the jvm.

线程将被启动并且 run() 方法将由 jvm 自动执行。

If the threads run-method is reading from a Stream, and it is the only one reading, it will not "miss" anything in that stream.

如果线程 run-method 正在从 Stream 中读取,并且它是唯一的读取,则它不会“错过”该流中的任何内容。

回答by jsight

Without more details, it is hard to give a complete answer. Nevertheless, here is the code for starting two threads:

没有更多的细节,很难给出完整的答案。不过,这里是启动两个线程的代码:

Thread thread1 = new Thread () {
  public void run () {
    // ... your code here
  }
};
Thread thread2 = new Thread () {
  public void run () {
    // ... your code here
  }
};
thread1.start();
thread2.start();

回答by Charlie Martin

Well, they won't run simultaneouslyunless you have a multiprocessor computer, but that's not usually the issue. What will happen is that each thread will get a slice of time, more or less alternatively.

好吧,除非您有一台多处理器计算机,否则它们不会同时运行,但这通常不是问题。将会发生的是,每个线程或多或少都会获得一段时间。

If you're losing I/O, it's probably not the threading that's your real problem. can you tell us how you're reading this stuff?

如果您正在丢失 I/O,那么您真正的问题可能不是线程。你能告诉我们你是如何阅读这些东西的吗?