Threads

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jun 2004
Posts: 609
Reputation: freesoft_2000 is an unknown quantity at this point 
Solved Threads: 8
freesoft_2000 freesoft_2000 is offline Offline
Practically a Master Poster

Threads

 
0
  #1
Feb 7th, 2005
Hi everyone,

I have a question about threads. Consider the below program

  1.  
  2. public class test
  3. {
  4.  
  5. public void test1()
  6. {
  7. System.out.println("Test 1");
  8. }
  9.  
  10. public void test2()
  11. {
  12. System.out.println("Test 2");
  13. }
  14.  
  15. public void test3()
  16. {
  17. System.out.println("Test 3");
  18. }
  19.  
  20. public static void main(String args[])
  21. {
  22. test a = new Jtest();
  23. a.test1();
  24. a.test2();
  25. a.test2();
  26. }
  27. }

As you can see above i have three methods in the above class. My question is how do i call each of these methods in a separate thread either in the class main or in the class itself

Consider the below method

  1.  
  2. public void test()
  3. {
  4. System.out.println("Test 1"); //command line 1
  5. System.out.println("Test 2"); //command line 2
  6. }

As you can see from the above method i have two command lines in the above method. My question is how do i call each command line in a separate thread.

Basically i need to know how to call a specific method or a specific command line in a separate thread excluding the main thread

I hope someone can help me with both these questions

Any help is greatly appreciated

Thank You

Yours Sincerely

Richard West
Reply With Quote Quick reply to this message  
Join Date: Nov 2004
Posts: 6,143
Reputation: jwenting is just really nice jwenting is just really nice jwenting is just really nice jwenting is just really nice 
Solved Threads: 213
Team Colleague
jwenting's Avatar
jwenting jwenting is offline Offline
duckman

Re: Threads

 
0
  #2
Feb 7th, 2005
You can pass a Runnable to a Thread.
Something like this will work
  1. // rest of your code ...
  2. public static void main(String[] args) {
  3. test t = new test();
  4. class R1 implements Runnable {
  5. test tt;
  6. public R1(test t) {tt=t;}
  7. public void run() {tt.test1();}
  8. }
  9. class R2 implements Runnable {
  10. test tt;
  11. public R2(test t) {tt=t;}
  12. public void run() {tt.test2();}
  13. }
  14. class R3 implements Runnable {
  15. test tt;
  16. public R3(test t) {tt=t;}
  17. public void run() {tt.test3();}
  18. }
  19. new Thread(new R1()).start();
  20. new Thread(new R2()).start();
  21. new Thread(new R3()).start();
  22. }

There are more elegant solutions using the reflection API.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC