Java Multithreading Basics (i)

Source: Internet
Author: User

First, the basic concept

The thread state graph consists of five states

1. New state: When the thread object is created, it enters the new state. For example, thread thread=new thread ();

2. Ready state (Runnable): Also known as "executable State". After the thread object is created, the other thread calls the object's start () method to start the thread. For example, Thread.Start (); a thread in the ready state can be executed at any time by CPU scheduling.

3. Running state (Running): Thread gets CPU permission to execute. Note that the thread can only enter the running state from the ready state.

4, blocking State (Blocked): Blocking state is the thread for some reason to abandon the use of the CPU, temporarily stop running. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three kinds of blocking situations:

(1), waiting for blocking: Let the thread wait for a job to complete by calling the thread's Wait () method.

(2), synchronous blocking: The thread acquires a synchronized synchronization lock failure (because the lock is occupied by another thread) and it goes into a synchronous blocking state.

(3), other blocking: When a call to the thread's sleep () or join () or an I/O request is made, the thread goes into a blocking state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.

5. Dead State (Dead): The thread finishes executing, or exits the run () method because of an exception, and the thread ends the life cycle.

Second, the realization of multithreading commonly used two ways: thread and runnable; "Thread pool (in Java.util.concurrent package) can also implement multi-threading, explained later"

1. Thread and runnable similarities and differences

(1) The same point: are "multi-threaded implementation mode."

(2) Different points: Runnable is the interface contains only a run () method, the implementation can define a class A implementation of the interface, through the new thread (new A ()) and other ways to create new threads. The Runnable interface code is as follows:

 Public Interface Runnable {    publicabstractvoid  run ();}

Thread is a class that implements the Runnable interface. For example: public class Thread implements Runnable {}

We know that "a class can have only one parent class, but it can implement multiple interfaces", so runnable has better extensibility. In addition, runnable can also be used for "resource sharing". That is, multiple threads are based on a

A Runnable object that shares the resources established on the Runnable object. It is generally recommended to implement multithreading through Runnable .

2. Thread Multithreading Example

The sample code is as follows:

Importjava.util.ArrayList; Public classMyThreadextendsThread {Private intTicket = 10; @Override Public voidrun () { for(inti = 0; I < 20; i++) {            if( This. ticket>0) {System.out.println ( This. GetName () + "Sell ticket: Ticket" + This. ticket--); }        }    }}Importorg.junit.Test; Public classthreadtest {@Test Public voiddemo1 () {//start three threads, T1,T2,T3; 10 tickets per threadMyThread T1 =NewMyThread (); MyThread T2=NewMyThread (); MyThread T3=NewMyThread ();        T1.start ();        T2.start (); T3.start ();//T1.run ();//T2.run ();//T3.run ();    }}
Thread Sample Code
thread-1 Sell Tickets: Ticket10thread-2 Sell Tickets: Ticket10thread-1 Sell Tickets: Ticket9thread-0 Sell Tickets: Ticket10thread-1 Sell Tickets: Ticket8thread-2 Sell Tickets: Ticket9thread-1 Sell Tickets: Ticket7thread-0 Sell Tickets: Ticket9thread-1 Sell Tickets: Ticket6thread-2 Sell Tickets: Ticket8thread-1 Sell Tickets: Ticket5thread-1 Sell Tickets: Ticket4thread-0 Sell Tickets: Ticket8thread-1 Sell Tickets: Ticket3thread-2 Sell Tickets: Ticket7thread-1 Sell Tickets: Ticket2thread-1 Sell Tickets: Ticket1thread-0 Sell Tickets: Ticket7thread-0 Sell Tickets: Ticket6thread-0 Sell Tickets: Ticket5ththread-0 Sell Tickets: ticket4
Run Results

The test method belongs to a main thread, where three sub-threads are created, and 10 tickets are sold per thread depending on thread security.

3. Runnable Multithreading Example

The sample code is as follows:

 PackageRunnabledemo; Public classMyThreadImplementsRunnable {Private intTicket = 10;  Public voidrun () { for(inti = 0; I < 20; i++) {            if( This. ticket > 0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Sell ticket: Ticket" + This. ticket--); }        }    }} PackageRunnabledemo;Importthreaddemo.threadtest;Importorg.junit.Test; Public classrunnabletest {@Test Public voiddemo1 () {MyThread MyThread=NewMyThread (); //Start three threads t1,t2,t3 (share a Runnable object), these three threads sell 10 tickets altogether.Thread T1 =NewThread (MyThread); Thread T2=NewThread (MyThread); Thread T3=NewThread (MyThread);        T1.start ();        T2.start ();    T3.start (); }}
runnable Sample Code
thread-1 Sell ticket: Ticket10thread-0 Sell ticket: Ticket9thread-1 Sell ticket: Ticket8thread-2 sell ticket: Ticket6thread -0 Sell ticket: Ticket7thread-2 Sell ticket: Ticket4thread-1 Sell ticket: Ticket5thread-2 sell ticket: Ticket2thread -0 Sell ticket: Ticket3thread-1 sell ticket: Ticket1
Run Results

The main thread creates and launches three child threads, and these three sub-threads are created based on the Mythread runnable object. The result of the operation shows that the three threads have sold 10 tickets together, indicating that they shared the runnable interface.

4. The start () and run () methods in thread are different
(1), the Run () method belongs to the main thread method, can be used as a common method, in the main thread in order to execute, not new thread, when the last run () method body execution, the next run () method can continue, not to achieve multi-threading purposes;

(2), Start () method to start the thread, the real implementation of multi-threaded operation. When the start () method starts the thread, the thread is in a ready state and is not running. Then the run () method of the thread class is implemented through the thread class call, and the Run () method runs the end flag thread termination. During the run () method execution, the other child threads do not have to wait for the run () method of a child thread to complete, but rather the CPU is dispatched to execute which child thread. The start () method cannot be called repeatedly, otherwise it throws a Illegalthreadstateexception exception

You can also run the code to see the current running thread name to determine

 PackageStartvsrun; Public classMyThreadextendsThread { PublicMyThread (String name) {Super(name); } @Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "is running"); }} PackageStartvsrun;Importthreaddemo.threadtest;Importorg.junit.Test; Public classSVSR {@Test Public voiddemo1 () {Thread MyThread=NewMyThread ("MyThread"); System.out.println (Thread.CurrentThread (). GetName ()+ "Call Mythread.run ()");        Mythread.run (); System.out.println (Thread.CurrentThread (). GetName ()+ "Call Mythread.start ()");    Mythread.start (); }}
Test Code
Main call Mythread.run () main was Runningmain call Mythread.start () MyThread is running
Run Results

Java Multithreading Basics (i)

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.