简体   繁体   English

同时运行2个线程

[英]Running 2 threads simultaneously

In the case of an IM client. 在IM客户端的情况下。 I have made 2 separate threads to handle sending packets (by std io) and receiving packets. 我已经做了2个单独的线程来处理发送数据包(通过std io)和接收数据包。 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? 问题是如何使这两个线程同时运行,以便我可以保持提示输入,同时随时准备接收数据包?

I have already tried setting a timer but the data is always lost receiving. 我已经尝试过设置定时器,但数据总是丢失接收。

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();

Well, they won't run simultaneously unless 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. 如果您正在丢失I / O,那可能不是线程是您真正的问题。 can you tell us how you're reading this stuff? 你能告诉我们你是怎么读这些东西的吗?

I think you might have missed something significant with either Threads, Streams or both :-) 我想你可能错过了Threads,Streams或两者都有重要意义:-)

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读取,并且它是唯一一个读取,它将不会“遗漏”该流中的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM