3

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.

Stu Thompson
  • 38,370
  • 19
  • 110
  • 156
lamsaitat
  • 53
  • 1
  • 3
  • 6

3 Answers3

21

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();
jsight
  • 27,819
  • 25
  • 107
  • 140
  • my send and receive threads rely on sending and listening on UDP socket respectively. from what i can understand, your sample codes seem to inject the thread in the code instantly. i have created a runnable class for them, so will your approach be applicable to such? – lamsaitat Apr 20 '09 at 16:22
  • I don't know what "inject the thread in the code instantly" means. Perhaps you can post sample code to further explain what you mean? – jsight Apr 20 '09 at 16:24
  • as in ur code is capable of creating a thread locally in a main – lamsaitat Apr 20 '09 at 16:50
  • @lamsait: My code creates new threads which run independently. These are created wherever you execute them. I agree with Karlp that you seem to have a fundamental misunderstaning of threads. – jsight Apr 20 '09 at 17:03
  • yes indeed, i have to admit that in writing this IM service program 70% of the syntax, methods and classes are never heard of before. Big thanks to both you and Karlp. – lamsaitat Apr 20 '09 at 17:19
7

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?

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
7

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.

KarlP
  • 5,149
  • 2
  • 28
  • 41