tags:

views:

126

answers:

2

Hello All!

How can I implement a run() method of thread if I create a Thread Global?

I mean If I create a Thread Globally then can I implement its run() method {" public void run()"} anywhere in my Application?

In the run() method I have to write the code to perform some action.

IF I can do it then please can anyone show me briefly how to do it particularly.

I am a bit confused!!!!!

Thanks, david

+4  A: 

Given the following class:

class MyWorker implements Runnable {
    @Override
    public void run() {
}

You can create and start a thread with:

Thread thread = new Thread(m_worker);
thread.setDaemon(true); // If the thread should not keep the process alive.
thread.setName( "MyThreadName" );
thread.start();

You can implement the Runnable as a top-level class, a nested class, or an anonymous class.

Multi-threaded programming requires special attention. Joshua Bloch's "Effective Java," 2nd ed., has an introduction to some issues in its "Concurrency" chapter. It would be worth reading. One suggestion is to prefer executors and tasks to raw threads.

Andy Thomas-Cramer
+1  A: 

A thread is represented by a Thread object. You create a Thread object as an anonymous inner class or by subclassing Thread with your own class that implements run(). Here is the anonymous version.

Thread t = new Thread() {
  public void run() {
     // Do something on another thread
  }
}

Here is the subclass version

class MyThread extends Thread() {
  public void run() {
    // Do something on another thread
  }
}
Thread t = new MyThread();

Typically you use an anonymous class for a quick and dirty operation and you create a subclass if the thread has a payload (parameters, result etc.)

Note that these snippets just declare the thread. To actually run the thread you must call start():

t.start();

That's it. When the thread starts, it invokes the run() on the new thread. The main thread and the new thread run in parallel.

More advanced topics like thread synchronisation should really be tackled when you've got the basics worked out.

locka
Which is the main Thread and the New Thread in the above Example?
david
The launching thread (which is not necessarily the application main thread) is the one that creates a Thread object and then calls start() on it. The contents inside the run() method are executed on the new thread. So if the run() method said System.out.println("hello world"), that command will be executed by the new thread. You could spawn off 5 instances of the thread and you would get 5 hello world messages, 1 per thread. When run() completes, the thread will be terminated so after saying hello world, all 5 threads would terminate.
locka
Thanks, Got it now
david