简体   繁体   中英

Threads in java

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM