Getting Started with Java--(4) multithreading

Source: Internet
Author: User

Keywords: threads, thread, Runnable, sleep (), yield (), join (), synchronization one, thread overview

In an operating system, each independently executed program can be called a process, which is a "running program". And in the process can have more than one execution unit at the same time, these execution units can be seen as a program of clues, called threads. The Java runtime environment is a single process that contains different classes and programs. Threads can be called lightweight processes. Threads require fewer resources to create and reside in a process, and can share resources in a process.

Second, the creation of the thread

1. Java provides two multi-threading implementations: ① A thread class that inherits the Java.lang package, and copies the thread class's run () method, implementing the code on the thread in the run () method, and providing a start () method for starting a new thread. Examples of creating objects are: MyThread mytread = new Mytread ();
1 public class EXAMPLE02 {2 public     static void main (string[] args) {3         MyThread MyThread = new MyThread () ;//Create thread MyThread thread Object 4         mythread.start ();//Turn on thread 5 while         (true) {       //print output by a dead Loop statement 6             System.out.println ( The main () method runs "            }10 class MyThread extends thread{11 public void run () { c16>) {System.out.println ("run () method of the MyThread class" }16}       
② an implementation of the Java.lang.Runnable interface, also implemented in the run () method of running code on the thread, providing a start () method to start a new thread. Examples of creating objects are: MyThread mytread = new Mytread (); Thread thread = new Thread (mytread);
 1 public class  EXAMPLE03 {2 public static void  main (string[] args) {3 MyThread MyThread = New MyThread ();//Create thread MyThread thread object 4 thread thread = new Thread (MyThread);//Create Thread Object 5 Thread.Start ();//Open thread         , the Run () method in the execution thread 6 while (true) {///through a dead Loop statement printout 7 System.out.println ("Main () method is running" ); 8  } 9 }10 }11 class MyThread implements  runnable{12 public void Run () {//thread of code snippet when the start () method is called, The thread starts at this point (true ) {System.out.println ("run () method of the MyThread class )", and }16 }17}   
2, the implementation of the Runnable interface to inherit the thread class has the following advantages: ① suitable for multiple threads of the same program code to handle the same resource situation, the thread with the program code, data effective separation ② can avoid the limitations of single-Inheritance in Java (a class can no longer inherit the thread class once it inherits a parent class). 3. The so-called background thread is a thread that provides a generic service in the background while the program is running, and this thread is not an integral part of the program. Therefore, when all non-background threads end, the program terminates and all background threads are killed. Conversely, the program does not terminate as long as any non-background thread (the user thread) is still running. A background thread terminates its run method without executing a finally clause. A child thread created by a background thread is also a background thread. When a thread object calls the Setdaemon (true) statement before it starts (before the start () method), the thread becomes a background thread. Three, the life cycle of the thread and the transition of state

1, the new state (new) cannot run at this time, only the Java virtual machine allocates memory for it. 2. Ready state (Runnable) when the thread object calls the start () method, the thread enters a ready state (also known as a running state), is in the running pool, has run conditions, can get the CPU right to start running, and waits for the system to dispatch. 3. The running state (Running) Ready thread gets the CPU right and starts executing the thread execution body in the run () method, the thread is running. Only threads that are in a ready state can transition to the running state. 4. Blocking state (Blocked) transitions from blocked state state to ready state: ① When a thread attempts to acquire a synchronization lock on an object, if the lock is held by another thread, the current thread goes into a blocking state, and if it wants to enter the ready state from the blocking state, it must acquire the locks held by other threads. ② when a thread invokes a blocking IO method, the thread goes into a blocking state and must wait until the blocked Io method returns if it wants to be in a ready state. ③ when a thread calls the wait () method of an object, it also causes the thread to go into a blocking state, which needs to be woken up by using the Notify () method if it wants to enter a ready state. ④ when a thread calls the sleep (long mills) method of thread, it also causes the thread to go into a blocking state, in which case the thread automatically enters the ready state when the thread is asleep. ⑤ when another thread's join () method is called in one thread, the current thread is put into a blocking state, in which case it is necessary to wait until the newly joined thread finishes running to end the blocking state and join the ready state. Note: The thread can only enter a ready state from the blocking state and cannot go directly to the running state. 5. The dead State (Terminated) thread runs out or the thread throws an uncaught exception, an error, and the thread enters the dead state. Once in a state of death, the thread will no longer have the qualification to run and cannot be converted to another state.   Four, thread scheduling 1, thread priority each Java thread has a priority, which helps the operating system determine the scheduling order of threads. The priority of a Java thread is an integer whose value range is 1 (thread.min_priority)-Ten (thread.max_priority). such as: Thread.setpriority (10); By default, each thread is assigned a normal 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.  2, Thread hibernation threadsThe. Sleep (long Millis) method declares that the inerruptedexception exception is thrown, so you should catch the exception when calling this method, or declare the exception to be thrown. The method is static and only controls the current thread hibernation.  
1 public classEXAMPLE08 {2 public static void Main (string[] args) throws exception{3//Creates a thread 4 new thread (new  sleepthread ()). Start (); 5 for (int i= 1;i<= 10;i++ ) {6 if (i==5 ) {7 thread.sleep (2000);//When the front thread sleeps 2 seconds 8 } 9 System.out.prin TLN ("Main thread is outputting:" +  i); Thread.Sleep (500);//When the front-thread sleeps 500 milliseconds }12 }13 }14 class Sleepthread Implements  runnable{15  @Override16 public void  Run () {(int i= 1;i<=10;i++ ) {(i==3< span>) {Try  {Thread.Sleep (+ ),}catch  (Interruptedexception e) {$  e.printstacktrace ( ); }24 }25 System.out.println ("line Cheng is outputting:" +  i); "Try  {Thread.Sleep (+ )} catch< span> (Exception e) { e.printstacktrace (); + }31 }32       span>                 
3, thread concession thread concessions can be achieved through the yield () method, which is similar to the sleep () method, it is possible for the currently running thread to pause, the difference is that the yield () method does not block the thread, it simply converts the thread into a ready state, so that the system scheduler again. When a thread calls the yield () method, only threads with the same priority or higher as the current thread can get the chance to execute.
1//Define Yieldthread class inherits the Thread Class 2 class Yieldthread extends thread{3//    defines a method for constructing a parameter 4 public      Yieldthread ( String name) {5             } 7      @Override 9 public     void Run () {Ten for         (int i= 0;i<5;i++< c13>) {System.out.println (Thread.CurrentThread (). GetName () + "___" +i), if (i==3) {System.out.print (" Thread Concession "}19 public class Example09 {public static void main (string[] args) {21//Create two threads x thread t1= new Yi Eldthread ("Thread A"); t2= new Yieldthread ("Thread B" }28 )      
4. Thread jump queue When a thread calls the join () method of another thread, the calling thread is blocked until the thread joined by the join () method is finished before it continues to run.
 1 public class  Example10 {2 public static void Main (string[] args) throws  exception{3//Created Threads 4 Thread t = new Thread (new Eemergencythread (), "thread One" ), 5  T.start (), 6 for (int i=1; i<6;i++ ) {7 System.out.println (Thread.CurrentThread (). GetName () + "input:" +  i); 8 if (i==2 ) {9 T.join (); Call the Join () method }11 Thread.Sleep (+ ), }13 }14 }15 class Eemergencythread IMPLEMENTS  runnable{16  @Override17 public void  Run () {$ for (int i =1;i<6;i++ ) {System.out.println (Threa D.currentthread (). GetName () + "input:" +  i), try  {thread.sleep (+ ), and}catch  ( Interruptedexception e) { e.printstacktrace (); }25 }26 }27}     /span>                
Five, multi-threaded synchronization 1, synchronous code block: Lock is a lock object, it is the key to synchronize the code block, it can be any type of object, but multiple threads shared lock object must be unique. "Arbitrary" is the type of the shared lock object.synchronized(lock) { Operation shared resource code block} 2. Synchronization method:
Synchronized returns a value type method name ([Parameter 1, ...] ){ }
3, synchronous code block and synchronous method to solve the thread security problem when the multi-thread accesses the shared data simultaneously, as long as the same lock is added, only one thread can execute at the same time, but the thread will judge the state of the lock every time while executing the synchronous code, which is very resource consuming and less efficient. Example:
1//define TICKET1 Class implementation runnable Interface 2 class Ticket1 implementsrunnable{3 private int tickets=10;         Define the variable tickets and assign a value of 10 4/* Synchronous code block usage 5 Object lock = new Object ();//define any object that is used as a lock for the synchronization code block 6 public void Run () {7                 while (true) {8 synchronized (lock) {9 try {Thread.Sleep (10); 11                 } catch (Interruptedexception e) {e.printstacktrace (); 13}14 if (tickets>0) {System.out.println (Thread.CurrentThread (). GetName () 16 + "--         -Sell Ticket "+ tickets--");}else{18 break;19} 20}21 }22}*/24 public voidRun () {.) {saleticket (); Call ticket method if (tickets<=0 ) {break ; }31 }32 }34//definition One synchronization Method Saleticket () synchronized void  Saleticket () {tickets>0 ) {PNs try  {THREAD.SL Eep (), e.printstacktrace} catch  (Interruptedexception e) {-- * * ();}42  System.out.println ( Thread.CurrentThread (). GetName () + "---sell ticket" + tickets--); }45 }46 }47 public class  E XAMPLE12 {n-public static void  main (string[] args) {Ticket1 ticket =new  Ticket1 (), New thread (Ticket, "thread 1 "). Start (); New thread (Ticket, Thread 2 ). Start (); The new thread (Ticket," Thread 4 "). Start (); Ticket, "Thread 3" ). Start ();}55 }           
4. Deadlock

A deadlock is a situation in which multiple threads are blocked at the same time, and one or both of them are waiting for a resource to be freed. The program cannot terminate gracefully because the thread is blocked indefinitely.

Four prerequisites for Java deadlock generation:

① mutually exclusive use, that is, when a resource is used (occupied) by one thread, other threads cannot use the

② can not be preempted, resource requester can not force from the resource holders to seize the resources, resources only by the resource holders to release voluntarily.

③ requests and holds, that is, when the resource requester requests other resources while maintaining possession of the original resources.

④ cycle Wait, that is, there is a waiting queue: P1 occupies P2 resources, P2 possession of P3 resources, P3 possession of P1 resources. This creates a waiting loop.

Six, multithreaded communication in the object class provides the Wait (), notify (), Notifyall () method to solve the communication problem of the thread, that is, to let the thread in a certain order in turn execution. Ways to wake up a thread:
Method declaration Function description
void Wait () Causes the current thread to discard the synchronization lock and enter the wait until another thread enters the synchronization lock and calls the Notify () method or the Notifyall () method to wake the thread
void Notify () Wake up this sync lock the thread waiting for the first call to the Wait () method
void Notifyall () Wake up this sync lock all threads calling the Wait () method
Wait (), notify (), Notifyall () The callers of these three methods should be synchronous lock objects, and if the callers of these three methods are not synchronous lock objects, the Java virtual machine throws illegalmonitorstateexception. Sample Access data:
1 classstorage{2 Private int[] cells =new int[10];//Array Storage array 3 private int inpos,outpos;//InPos represents an array subscript at deposit, Outpos represents a fetch         Out-of-time array subscript 4 private int count;//The number of data deposited or taken out 5 public synchronized void put (int num) {//define a put () method to deposit data into the array 6 Try{7//If the data is placed equal to the length of cells, this thread waits 8 while (count = =Cells.length) {9 This. Wait (); 10}11 Cells[inpos] = num;//put data into the array System.out.println ("cells[" + InPos + "] put data---" +Cells[inpos]) inpos++;//the position of the element to be added if (InPos = =cells.length) InPos = 0;//when the inPos array length is 10, it is set to 016 count++;. notify ();}catch(Exception e) {19E.printstacktrace (); 20}21}22//define a Get () method to remove data from an array synchronized voidGet () {try{while (count==0) {This. Wait (); 27}28 int Data=Cells[outpos];29 System.out.println ("Extract data from cells[" +outpos+ "] +Data), 31 outpos++ is currently present when cells[outpos]=0;//is removed; After the element is taken, the position is added to the IF (outpos==Cells.length) outpos=0; count--;//each take out an element count minus 135 this. notify ();}catch(Exception e) {37E.printstacktrace (); 38}39}40}41 class Input implements runnable{//Input thread class-PrivateStorage st;43 private int num;//define a variable num44 Input (Storage st) {//Receive a Storage object by constructing method this.st= st;46}47 PU Blic void Run () {$ while (true) {st.put (num++);//num is stored in an array, num is automatically added after each deposit }51 }52 }53 class Output im Plements runnable{//Output thread class Storage private st;55 output (Storage st) {//through construction method receives a Storage object, this.st= st;57 c10>}58 public void Run () {$st.get ();//loop out element }62 }63 }64 public class  EXAMPLE17 {n-a public static void main (string[] args) {Storage st=new Storage ();//Create an array storage class object. Input input=new Inpu T (ST);//Create input object incoming storage object output=new output output (ST);//Create Output object incoming storage object, new Thread (Input). Start ();/ Open new Thread (output). Start ();//Start new thread }73}        

Run results

CELLS[1] Put data---214311cells[2] put data---214312cells[3] put data---214313 cells[4] intothe data---214314cells[ 5] Put data---214315cells[6] into data---214316 cells[7] put data---214317 cells[8] intothe data---214318 cells[9] Put data---214319cells[0] into data---214320 remove data from cells[1] 214311 extract data from cells[2]214312 from Cells[3] Extracting data from cells[4] 214314 (from the cells[5] (214315) remove data from thecells[6] 214316 from Cells[7] Remove data from the cells[8] 214317 from the cells[9] to remove data214319 from cells[0] to remove the data 214320    

Examples of multithreading accumulation:

Simulate 10 threads, the first thread from 1 to 10, the second thread from 11 to 20 ... The tenth thread is added from 91 to 100, and finally the results of the 10 threads are added.

1 public class Accumulator extendsThread {2 private int stratnum; 3 public static int  SUM, 4 public accumulator (int  startnum) {5 This.stratnum =  startnum; 6 } 7 public static synchronized void Add (int  num) {8 sum + =  num; 9 }10 Publ IC void  Run () {one int sum = 0 ; (int i = 0; i < i++ ) {sum + = Stratnum +  i;14  }15  Add (sum); }17 public static void Main (string[] args) throws  Exception {thread[] Threadlist = new thread[10 ];19 for (int i = 0; i <; i++ ) {Threadlist[i] = new Accumulator (Ten * i + 1 ); 21 span> Threadlist[i].start (); }23 for (int i = 0; i <; i++ ) { threadlist[i].join ();  }26 System.out.println ("sum is:" +  sum); }28}          

Getting Started with Java--(4) multithreading

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.