954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Threads

Hi everyone,

I have a question about threads. Consider the below program

public class test
{

public void test1()
{
    System.out.println("Test 1");
}

public void test2()
{
    System.out.println("Test 2");
}

public void test3()
{
   System.out.println("Test 3");
}

public static void main(String args[])
{
   test a = new Jtest(); 
   a.test1();
   a.test2();
   a.test2();
}
}


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

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


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

freesoft_2000
Practically a Master Poster
623 posts since Jun 2004
Reputation Points: 25
Solved Threads: 10
 

You can pass a Runnable to a Thread.
Something like this will work

// rest of your code ...
public static void main(String[] args) {
  test t = new test();
  class R1 implements Runnable  {
    test tt;
    public R1(test t) {tt=t;}
    public void run() {tt.test1();}
  }
  class R2 implements Runnable  {
    test tt;
    public R2(test t) {tt=t;}
    public void run() {tt.test2();}
  }
  class R3 implements Runnable  {
    test tt;
    public R3(test t) {tt=t;}
    public void run() {tt.test3();}
  }
  new Thread(new R1()).start();
  new Thread(new R2()).start();
  new Thread(new R3()).start();
}


There are more elegant solutions using the reflection API.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You