Latest web development tutorials

Java multi-threaded programming

Java multi-threaded programming to provide built-in support. A multithreaded program contains two or more portions can run concurrently. Each part of the program is called a thread, and each thread defines a separate path of execution.

Multithreading is a special form of multi-tasking, multi-threading, but use a smaller resource overhead.

Another term is defined herein, and thread-related - process: a process including the operating system allocates memory space that contains one or more threads. A separate thread can not exist, it must be part of the process. A process has been running to the end of all the non-waiting until after the end of the thread to run.

Multithreading can meet programmers to write efficient program to reach full CPU utilization purposes.


A thread's life cycle

Thread through all stages of its life cycle. The following figure shows the complete life cycle of a thread.

java_thread

  • New Status:

    After using the new keyword and the Thread class or subclass to create a thread object, the thread object is in a new state. It remains in this state until the program start () this thread.

  • Ready state:

    When a thread object to call the start () method, the thread into the ready state. Ready thread in the ready queue, to wait for the JVM thread scheduler scheduling.

  • Operating status:

    If the thread gets ready state of CPU resources, you can perform run (), the thread will be running at this time. Thread running the most complex, it can become blocked state, ready state, and the state of death.

  • Blocked state:

    If a thread is executed after sleep (sleep), suspend (hang) and other methods, the loss of occupied resources, the thread enters the blocked state from running. After the sleep time has come to get equipment or resources to re-enter the ready state.

  • Death Status:

    When a thread running state of the task or other termination condition occurs, the thread is switched to the end state.


A thread's priority

Each Java thread has a priority, which helps determine the operating system thread scheduling order.

Java thread's priority is an integer which ranges from 1 (Thread.MIN_PRIORITY) - 10 (Thread.MAX_PRIORITY).

By default, each thread is assigned a priority NORM_PRIORITY (5).

Thread with a higher priority is more important to the program, and should allocate processor resources before low priority threads. However, the order does not guarantee thread priority thread of execution, and is very dependent on the internet.


Create a thread

Java provides two methods to create a thread:

  • Runable by implementing the interface;
  • Through inheritance Thread class itself.

To create a thread by implementing Runnable interface

Create a thread, the easiest way is to create a class that implements the Runnable interface.

In order to achieve Runnable, a class need only perform a method call run (), the following statement:

public void run()

You can override this method, it is important to understand the run () can call other methods, the use of other classes, and declare a variable, just as the main thread.

After creating a class implements Runnable interface, you can instantiate an object in the class a thread.

Thread defines several constructors, are following this we often use:

Thread(Runnable threadOb,String threadName);

Here, threadOb is an instance of a class that implements the Runnable interface, and threadName specify the new name of the thread.

After the new thread is created, you call its start () method it will run.

void start();

Examples

Here is an instance of it to create a thread and start execution of:

// 创建一个新的线程
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // 创建第二个新线程
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // 开始线程
   }
  
   // 第二个线程入口
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // 暂停线程
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}
 
public class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // 创建一个新线程
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}

Compile the above program runs as follows:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

To create a thread through inheritance Thread

The second way to create a thread is to create a new class that inherits the Thread class, and then create an instance of a class.

Inheriting class must override the run () method, which is the entry point for the new thread. It also must call the start () method to execute.

Examples

// 通过继承 Thread 创建线程
class NewThread extends Thread {
   NewThread() {
      // 创建第二个新线程
      super("Demo Thread");
      System.out.println("Child thread: " + this);
      start(); // 开始线程
   }
 
   // 第二个线程入口
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
                            // 让线程休眠一会
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
      }
      System.out.println("Exiting child thread.");
   }
}
 
public class ExtendThread {
   public static void main(String args[]) {
      new NewThread(); // 创建一个新线程
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Main Thread: " + i);
            Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}

Compile the above program runs as follows:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Thread Methods

The following table lists the Thread class some important ways:

No. Method Description
1 public void start ()
Make this thread to begin execution; Java Virtual Machine calls the run method of this thread.
2 public void run ()
If this thread was constructed using a separate Runnable run object, then call the run method of the Runnable object; otherwise, this method does nothing and returns.
3 public final void setName (String name)
Change the name of this thread, so that the same parameter name.
4 public final void setPriority (int priority)
Change the thread priority.
5 public final void setDaemon (boolean on)
Marks this thread as a daemon thread or a user thread.
6 public final void join (long millisec)
Wait for this thread to a maximum of millis milliseconds.
7 public void interrupt ()
Interrupted thread.
8 public final boolean isAlive ()
Tests if this thread is active.

Tests if this thread is active. The above method is called Thread object. The following method is a static method of the Thread class.

No. Method Description
1 public static void yield ()
Suspend the currently executing thread object, and perform other threads.
2 public static void sleep (long millisec)
Within a specified number of milliseconds currently executing thread to sleep (cease execution), this operating system timers and schedulers by the precision and accuracy of.
3 public static boolean holdsLock (Object x)
If and only if the current thread holds the monitor lock on the specified object, it returns true.
4 public static Thread currentThread ()
It returns a reference to the currently executing thread object is.
5 public static void dumpStack ()
The current thread's stack trace prints to the standard error stream.

Examples

The following program demonstrates some of the ways ThreadClassDemo Thread class:

// 文件名 : DisplayMessage.java
// 通过实现 Runnable 接口创建线程
public class DisplayMessage implements Runnable
{
   private String message;
   public DisplayMessage(String message)
   {
      this.message = message;
   }
   public void run()
   {
      while(true)
      {
         System.out.println(message);
      }
   }
}
// 文件名 : GuessANumber.java
// 通过继承 Thread 类创建线程

public class GuessANumber extends Thread
{
   private int number;
   public GuessANumber(int number)
   {
      this.number = number;
   }
   public void run()
   {
      int counter = 0;
      int guess = 0;
      do
      {
          guess = (int) (Math.random() * 100 + 1);
          System.out.println(this.getName()
                       + " guesses " + guess);
          counter++;
      }while(guess != number);
      System.out.println("** Correct! " + this.getName()
                       + " in " + counter + " guesses.**");
   }
}
// 文件名 : ThreadClassDemo.java
public class ThreadClassDemo
{
   public static void main(String [] args)
   {
      Runnable hello = new DisplayMessage("Hello");
      Thread thread1 = new Thread(hello);
      thread1.setDaemon(true);
      thread1.setName("hello");
      System.out.println("Starting hello thread...");
      thread1.start();
     
      Runnable bye = new DisplayMessage("Goodbye");
      Thread thread2 = new Thread(bye);
      thread2.setPriority(Thread.MIN_PRIORITY);
      thread2.setDaemon(true);
      System.out.println("Starting goodbye thread...");
      thread2.start();
 
      System.out.println("Starting thread3...");
      Thread thread3 = new GuessANumber(27);
      thread3.start();
      try
      {
         thread3.join();
      }catch(InterruptedException e)
      {
         System.out.println("Thread interrupted.");
      }
      System.out.println("Starting thread4...");
      Thread thread4 = new GuessANumber(75);
     
           thread4.start();
      System.out.println("main() is ending...");
   }
}

Results are as follows, the results of each run are not the same.

Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.

Thread several major concepts:

When multithreaded programming, you need to understand the following concepts:

  • Thread Synchronization
  • Communication between threads
  • Thread deadlock
  • Thread control: Suspend, stop and resume

Use multiple threads

The key to effective use of multi-threaded programs are concurrent execution is understood rather than serial execution. For example: The program has two subsystems need to execute concurrently, this time you need to take advantage of multi-threaded programming.

Through the use of multiple threads, you can write a very efficient program. However, please note that if you create too many threads, the efficiency of program execution is actually reduced, rather than enhanced.

Remember, the context switch overhead is also very important, if you create too many threads, CPU time spent in context switching time of execution of the program will be more!