Results 1 to 6 of 6
- 04-05-2010, 04:13 PM #1
Member
- Join Date
- Nov 2009
- Posts
- 41
- Rep Power
- 0
Executing two threads simultaneously.
Hello,
I have two threads and I want to execute them simultaneously.
This is my code:
This, however, executes Thread a first and then after Thread a is finished it executes Thread b.Java Code:public final class MainClass { public static void main(String[] args){ Thread a = new MyThread(doa); Thread b = new MyThread(dob); a.run(); b.run(); } }
But I want to run them simultaneously. How do I do that?
- 04-05-2010, 04:15 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,398
- Blog Entries
- 7
- Rep Power
- 17
- 04-05-2010, 06:46 PM #3
Member
- Join Date
- Nov 2009
- Posts
- 41
- Rep Power
- 0
Ok, now a new question.
How can I make two threads run alternatively?
Thread A
Thread B
Thread A
Thread B
Thread A
Thread B
etc.
I want to do it with a control variable, but it doesn't work out.
- 04-05-2010, 06:57 PM #4
- 04-05-2010, 07:35 PM #5
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,398
- Blog Entries
- 7
- Rep Power
- 17
- 04-05-2010, 08:03 PM #6
unless you have a mulicore-processor this is not really possible. the jvm switches between threads that fast that it looks like "simulaneously", but it isn't. and you can't force when a threads has to be started, the threads-scheduler decide when. nevertherless here is a bit of code that simulate something like you want.
Java Code:public class MyThread extends Thread { public void run() { while (true) { try { System.out.println("Hallo, I'm thread " + this.getName()); this.sleep(5); } catch (InterruptedException ex) { ex.printStackTrace(); } } } public static void main(String[] args) { MyThread a = new MyThread(); MyThread b = new MyThread(); a.start(); b.start(); } }
the principle is simple. after a thread has prompted "Hallo, I'm ..." it sleeps for 5 milliseconds so that the other thread can be started. watch out: the example has a endless while-loop.Last edited by j2me64; 04-05-2010 at 08:06 PM.
Similar Threads
-
newbie drawing two circles simultaneously
By nadeemshafi9 in forum Threads and SynchronizationReplies: 7Last Post: 01-09-2011, 01:53 PM -
Multiple persistance unit simultaneously, issue.
By afrodom in forum Enterprise JavaBeans (EJB)Replies: 1Last Post: 03-06-2010, 05:04 PM -
Why my threads don't run simultaneously?
By Gilvan Justino in forum New To JavaReplies: 7Last Post: 01-16-2010, 01:43 AM -
Executing .exe from java
By rp181 in forum Advanced JavaReplies: 6Last Post: 09-21-2009, 03:32 PM -
Enabling clients to simultaneously download a file
By DannyZB in forum NetworkingReplies: 1Last Post: 12-21-2008, 09:06 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks