java Thread

fabiodelorenzo
Posts: 65
Joined: Thu Oct 03, 2013 5:54 pm

java Thread

Postby fabiodelorenzo » Thu Oct 03, 2013 6:20 pm

Code: Select all

Runnable r = new Runnable() {
  public void run() {
  try {
      while (true) {
        System.out.println("Hello, world!");
        Thread.sleep(1000L);
      }
    } catch (InterruptedException iex) {}
  }
};


Runnable is actually an interface, with the single run() method that we must provide.

Code: Select all

Thread thr1 = new Thread(r);
thr1.start();



Different way to create the thread
The Runnable implementations that we created were inline classes. That is, we didn't spell out a full class declaration. But strictly speaking, the way to create a Runnable— or rather, a class that implements the Runnable interface— is as follows:

Code: Select all

public class MessagePrinter implements Runnable {
  private final String message;
  private final long interval;
  public MessagePrinter(String msg, long interval) {
    this.message = msg;
    this.interval = interval;
  }
  public void run() {
    try {
      while (true) {
        System.out.println(message);
        Thread.sleep(interval);
      }
    } catch (InterruptedException iex) {}
  }
}
MessagePrinter thr = new MessagePrinter();
thr.start();




Stopping a thread
A common solution is to use an explicit "stop request" variable, which we check on each pass through the loop. This technique is suitable provided that we can check the variable frequently enough:

Code: Select all

private volatile boolean stopRequested = false;

public void run() {
  while (!stopRequested) {
    ...
  }
}

public void requestStop() {
  stopRequested = true;
}



The above pattern is generally suitable if the variable stopRequested can be polled frequently. However, there is an obvious problem if the method blocks for a long time, e.g. by calling Thread.sleep() or waiting on an object.

Stopping a thread: Use Thread.interrupt()

In a typical producer-consumer pattern, where a thread blocks waiting on a queue (e.g. a BlockingQueue), we could organise for the thread to interpret some special object on the queue to mean "please shut down". To ask the thread to shut down, we therefore post the special message object to the queue. The advantage of this method is that the thread will finish processing messages already on the queue before shutting down.

Return to “java j2ee jsp”

Who is online

Users browsing this forum: No registered users and 0 guests