How can I start multithreaded programming

Java multi-thread programming

Java multi-thread programming support to provide built-in. A multi-threaded program contains two or more parts that can run at the same time. 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 less resources.

Another term is defined here and in relation to threads - Process: a process, including the operating system, reserves memory space that contains one or more threads. A separate thread cannot exist; it has to be part of the process. There was a procedure to run until the end of all non-waiting runs after the end of the thread.

Multithreading allows programmers to write efficient program to achieve full CPU usage purposes.


One thread of the life cycle

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

  • New status:

    the new Keyword and the Thread - Class or subclass to create a thread object After use, the thread object is in a new state. It remains in this state until Program start () this thread.

  • Ready - Status:

    When a thread object calls the start () method, the thread goes into the ready state. Ready thread in the ready queue, waiting for the JVM thread scheduler scheduling.

  • Operating condition:

    When the thread gets the CPU resource ready state, you can run (), the thread will be running at this point. Perform the most complex running, it can be clogged state, ready state, and state of death.

  • Blocked state:

    When a thread is running after sleep (sleep), suspend (hang) and other methods, the loss of occupied resources, the thread occurs to the blocked state it can run. After the rest period has equipment or resources available, enter the standby mode again.

  • TheDeath status:

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


One thread priority

Each Java thread has a priority which the operating system's thread scheduling order can determine.

Java thread priority is an integer ranging from 1 (Thread.MIN_PRIORITY) in the range - 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 lower priority threads. However, the job thread does not guarantee the thread priority of execution and is very dependent on the Internet.


Create a thread

Java offers two methods of creating a thread:

  • Mobile implemented through the interface;
  • By inheritance thread class itself.

to create a thread through the implementation of Runnable Interface

Creating a thread is the easiest way to create a class that implements the runnable interface.

In order to achieve runnable, a class only needs to execute a run () method call, the following statement:

public void run ()

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

After creating a class implemented runnable interface, you can instantiate an object in the class on a thread.

Subject defined several designers are following these we often use:

Thread (Runnable threadOb, String threadName);

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

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

void start ();

Examples

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

// 创建 一个 新 的 线程 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 works like this:

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 theme

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 the class must override the run () method, which is the entry point for the new thread. It must also call the Home Screen () method to run.

Examples

// 通过 继承 Thread 创建 线程 class NewThread extends Thread {NewThread () {// 创建 第二 个 新 线程 super ("Demo Thread"); System.out.println ("Child thread:" + this); begin(); // 开始 线程} // 第二 个 线程 入口 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 works like this:

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.

Themed methods

The following table lists some of the important possibilities of the Thread class:

No . Method description
1 public void start ()
Make this thread - Execution too start; The Java Virtual Machine calls the run method of this thread.
2 public void run ()
If this thread was constructing 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 it is 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 milliseconds.
7 public void interrupt ()
Broken thread.
8 public final boolean IsAlive ()
Checks whether this thread is active.

Checks whether this thread is active. The above procedure is called the thread object. The following method is a static method of the Thread class.

No . Method description
1 public static void yield ()
Append the currently running thread object and other threads to run.
2 public static void sleep (long millisec)
Within a certain number of milliseconds at the time running thread to sleep (no longer running), this operating system timer and dispatcher through the precision and accuracy of the.
3 public static boolean holdsLock (Object x)
If and only if the current thread holds the screen lock on the specified object, it returns true.
4 public static topic current ()
There is a reference to the thread object that is currently running.
5 public static void dumpStack ()
The stack trace of the current thread prints on the standard fault stream.

Examples

The following program shows some of the ThreadClassDemo thread class possibilities:

// 文件 名: 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, with the results of each run not being 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 important concepts:

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

  • Topic synchronization
  • Communication between threads
  • Thread deadlock
  • Thread control: suspend, stop and resume

Use multiple threads

The keys to effectively using multi-threaded programs are concurrent execution rather than serial execution. For example: the program has two subsystems that need to run at the same time, this time you need to take advantage of multi-threaded programming.

By using multiple threads, you can write a very efficient program. Note, however, that if you create too many threads, program execution efficiency is actually reduced, rather than improved.

Remember, the context switch overhead is also very important, if you create too many threads, CPU time related to time spent executing the program switching becomes more!