简体   繁体   中英

Running 2 threads simultaneously

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?

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. can you tell us how you're reading this stuff?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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