Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Beginner Threader Two thread running

 
Edward Bloom
Ranch Hand
Posts: 34
Eclipse IDE Fedora Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy!

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(MyThreaderDemo.java:9)
at tester.MyThreaderDemo.main(MyThreaderDemo.java:14)
.
..
...
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
Rancher
Posts: 2756
32
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
Eclipse IDE Fedora Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic