File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Beginner Threader Two thread running Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Beginner Threader Two thread running" Watch "Beginner Threader Two thread running" New topic

Beginner Threader Two thread running

Edward Bloom
Ranch Hand

Joined: Apr 10, 2012
Posts: 34


Here is my code:

The result is:

Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at tester.MyThreaderDemo.runner(
at tester.MyThreaderDemo.main(
0 Jamaica
1 Jamaica
2 Jamaica
3 Jamaica
4 Jamaica
5 Jamaica
6 Jamaica
7 Jamaica
8 Jamaica
9 Jamaica
DONE! Jamaica

I would like to print these in a thr2 thread: ". .. ..." until the thr1 thread finish.

Sorry for my creepy english.

Does someone have any idea how to change this code?
Thank you in advance for any help you can provide.
Jayesh A Lalwani
Saloon Keeper

Joined: Jan 17, 2008
Posts: 2746

The reason you are getting an exception in because you are trying to start a thread that is already running. You can start a thread only once.

What you need to do is give a reference of thr1to thr2. Inside the run method of thr2 call is alive on thr1 in a loop and print whatever you need to print. The main method should start both threads only once, and then wait for both threads to complete

BTW, I know you are probably practicing, but having 2threads dependent on each other is usually not good Design. The reason you start multiple threads is because you want something to execute in parallel, and having one thread wait for another defeats the purpose. In cases where threads wait for each other, you usually use a mutex or a semaphore
Edward Bloom
Ranch Hand

Joined: Apr 10, 2012
Posts: 34

Dear Jayesh!

Thank you so much for your reply.
Yes, I am practicing, i wonder how could be solved this problem with two thread.

I modified my code like this and it is work.

Anyway thank you for your comment!
I agree. Here's the link:
subject: Beginner Threader Two thread running
It's not a secret anymore!