Java Tour _ Advanced Tutorials _ Multithreaded Programming

Source: Internet
Author: User
Tags stack trace thread class

Excerpt from: http://www.runoob.com/java/java-multithreading.html

Java multithreaded Programming

Java provides built-in support for multithreaded programming. A thread refers to an execution path in a process that can be concurrent with multiple threads, with each thread performing different tasks in parallel.

Multithreading is a special form of multitasking, but multithreading uses a much smaller resource overhead.

Here you define another term related to threading-process: a process that includes the memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently, it must be part of a process.

A process runs until all non-daemon threads have finished running before the end.

Multithreading can satisfy programmers to write high-efficiency programs to achieve the full use of CPU.

The life cycle of a thread

A thread is a process that executes dynamically, and it also has a process from generation to death.

Shows the full life cycle of a thread.

    • New status:

When a thread object is established using the New keyword and the thread class or its subclasses, the thread object is in the new state. It keeps this state until the program start () this thread.

    • Ready state:

When the thread object calls the start () method, the thread enters the ready state. The ready state thread is in the ready queue, waiting for the thread scheduler in the JVM to dispatch.

    • Running Status:

If the ready state thread gets the CPU resources, it can execute run (), at which point the thread is in the running state. A running thread is the most complex and can become a blocking state, a ready state, and a dead state.

    • Blocking Status:

If a thread executes a method such as sleep (), suspend (), and then loses the resource, the thread enters the blocking state from the running state.

You can re-enter the ready state after the sleep time has arrived or the device resource has been acquired. Can be divided into three kinds:

    1. Wait for blocking: the thread in the running state executes the wait () method, which causes the thread to enter a wait-blocking state.
    2. Synchronous blocking: The thread acquires a synchronized synchronization lock failure (because the synchronization lock is occupied by another thread).
    3. Other blocking: When an I/O request is made by the calling thread's sleep () or join (), the thread enters the blocking state. When the sleep () state times out, the join () waits for the thread to terminate or time out, or the I/O process completes and the thread is re-entered in a ready state.
    • Death Status:

When a running state thread finishes a task or other termination condition occurs, the thread switches to the terminating state.

Priority of the thread

Each Java thread has a priority, which helps the operating system determine the order in which the threads are dispatched.

The priority of a Java thread is an integer whose value range is 1 (thread.min_priority)--10 (thread.max_priority).

By default, each thread will be assigned a priority of norm_priority (5).

A thread with a higher priority is more important to the program, and the processor resources should be allocated before a low-priority thread. However, thread precedence does not guarantee the order in which threads are executed, and is very dependent on the platform.

Create a thread:

Java provides three ways to create threads:

    • By implementing the Runnable interface
    • By inheriting the Thread class itself
    • Creating threads from callable and future

To create a thread by implementing the Runnable interface

The simplest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class simply executes a method call to run (), declared as follows:

 Public void Run ()

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

After you have created a class that implements the Runnable interface, you can instantiate a thread object in the class.

Tread defines several construction methods, and the following is what we often use:

Thread (Runnable threadob,string threadname);

Here, Threadob is an instance of the class that implements the Runnable interface, and ThreadName specifies the name of the new thread.

After the new thread is created, you call it's start () method before it runs.

void start ();

Here is an instance of creating a thread and starting to make it execute:

classRunnabledemoImplementsrunnable{PrivateThread t; PrivateString ThreadName; Runnabledemo (String name) {ThreadName=name; System.out.println ("Creating" +threadname); }         Public voidrun () {System.out.println ("Running" +threadname); Try{             for(inti=4; i>0; i--) {System.out.println ("Thread" + ThreadName + "," +i); Thread.Sleep (50); }        }Catch(interruptedexception e) {System.out.println ("Thread" + ThreadName + "interrupted."); } System.out.println ("Thread" + ThreadName + "exiting."); }         Public voidstart () {System.out.println ("Starting" +threadname); if(T = =NULL) {T=NewThread ( This, ThreadName);        T.start (); }    }    } Public classtestthread{ Public Static voidMain (string[] args) {Runnabledemo R1=NewRunnabledemo ("Thread-1");                R1.start (); Runnabledemo R2=NewRunnabledemo ("Thread-2");    R2.start (); }}

The operation results are as follows

CreatingThread-1startingthread-1creatingthread-2startingthread-2Runningthread -2threadthread-2,4runningthread-1threadthread-1,4threadthread-2,3  Threadthread-1,3threadthread-1,2threadthread-2,2threadthread-2,1  Threadthread-1,1threadthread-1exiting. Threadthread-2exiting.

To create a thread by inheriting thread

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

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

Although this method is listed as a multi-threaded implementation, it is also an example of implementing the Runnable interface in essence.

classThreaddemoextendsthread{PrivateThread t; PrivateString ThreadName; Threaddemo (String name) {ThreadName=name; System.out.println ("Creating" +threadname); }         Public voidrun () {System.out.println ("Running" +threadname); Try{             for(inti=4; i>0;i--) {System.out.println ("Thread:" +threadname+ "," +i); Thread.Sleep (50); }        }Catch(interruptedexception e) {System.out.println ("Thread:" +threadname+ "interrupted."); } System.out.println ("Thread:" +threadname+ "exiting."); }         Public voidstart () {System.out.println ("Starting" +threadname); if(T = =NULL) {T=NewThread ( This, ThreadName);        T.start (); }    }} Public classtestthread2{ Public Static voidMain (string[] args) {Threaddemo T1=NewThreaddemo ("Thread-1");                T1.start (); Threaddemo T2=NewThreaddemo ("Thread-2");    T2.start (); }}

Run results

CreatingThread-1startingthread-1creatingthread-2startingthread-2Running Thread -1thread:thread-1,4Running Thread-2thread:thread-2,4thread:thread-2,3 thread:thread-1,3thread:thread-2,2thread:thread-1,2thread:thread-1,1 thread:thread-2,1thread:thread-1exiting. Thread:thread-2exiting.

Thread method

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

Serial number Method description
1

public void Start ()

Causes the thread to start executing, and the Java Virtual machine calls the thread's Run method.

2

public void Run ()

If the thread is constructed using a standalone Runnable run object, the Run method of the Runnable object is called, otherwise the method does nothing and returns.

3

Public final void SetName (String name)

Change the thread name so that it is the same as the parameter name.

4

Public final void SetPriority (Int. priority)

The priority of the thread to be rerouted.

5

Public final void Setdaemon (Boolean on)

Mark the thread as either a daemon thread or a user thread.

6

Public final void Join (long millisec)

The maximum time to wait for the thread to terminate is Millis milliseconds.

7

public void Interrupt ()

The thread is disconnected.

8

Public Final Boolean isAlive ()

Tests whether the thread is active.

The above method is called by the Thread object. The following method is a static method of the Thread class.

Serial number Method description
1

public static void Yield ()

Pauses the currently executing thread object and executes other threads.

2

public static void sleep (long millisec)

Lets the currently executing thread hibernate (suspends execution) within the specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler.

3

public static Boolean Holdslock (Object x)

Returns true if and only if the monitor lock is persisted on the specified object by the front thread.

4

public static Thread CurrentThread ()

Returns a reference to the currently executing thread object.

5

public static void DumpStack ()

Prints the stack trace of the current thread to the standard error stream.

The following Threadclassdemo program demonstrates some of the methods of the thread class:

 PackageJavalearn;//implementing the Runnable interfaceclassDisplayMessageImplementsrunnable{PrivateString message;  Publicdisplaymessage (String message) { This. Message =message; }         Public voidrun () { while(true) {System.out.println (message); }    }}//inherit the thread classclassGuessanumberextendsthread{Private intNumber ;  PublicGuessanumber (intNumber ) {         This. Number =Number ; }         Public voidrun () {intCounter = 0; intGuess = 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.**"); }} Public classthreadclassdemo{ Public Static voidMain (string[] args) {Runnable Hello=NewDisplayMessage ("Hello"); Thread Thread1=NewThread (hello); Thread1.setdaemon (true); Thread1.setname ("Hello"); System.out.println ("Starting Hello thread ...");                Thread1.start (); Runnable Bye=NewDisplayMessage ("Goodbye"); Thread thread2=NewThread (bye);        Thread2.setpriority (thread.min_priority); Thread2.setdaemon (true); System.out.println ("Starting Goodbye thread ...");                Thread2.start (); System.out.println ("Starting thread3 ..."); Thread thread3=NewGuessanumber (27); Thread3.setname ("Thread3");        Thread3.start (); Try{thread3.join (); }Catch(interruptedexception e) {System.out.println ("Thread interrupted ..."); } System.out.println ("Starting thread4 ..."); Thread Thread4=NewGuessanumber (75); Thread4.setname ("Thread4");        Thread4.start (); System.out.println ("Main () is ending ..."); }}

Two ways to create a thread contrast

    • 1. When creating multi-threading in a way that implements the Runnable interface, the thread class simply implements the Runnable interface and can inherit other.
    • 2. When creating multi-threading in a way that inherits the thread class, writing is simple and if you need access to the current thread, you do not need to use the Thread.CurrentThread () method to get the current thread directly using this.

Several key concepts of threading

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

    • Thread synchronization
    • Inter-thread communication
    • Thread deadlock
    • Line programmed: Suspend, stop and resume

Use of multithreading

The key to effective use of multithreading is to understand that programs are executed concurrently rather than serially. For example, there are two subsystems in the program that need to be executed concurrently, which requires multithreaded programming.

Through the use of multithreading, you can write a very efficient program. Note, however, that if you create too many threads, the efficiency of the program execution is actually reduced, not promoted.

Keep in mind that the context switching overhead is also important, if you create too many threads, the CPU spends more time switching the context than executing the program!

Java Tour _ Advanced Tutorials _ Multithreaded Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.