Java getting started -- (4) multithreading, java getting started Multithreading

Source: Internet
Author: User

Java getting started -- (4) multithreading, java getting started Multithreading
Key words: Thread, Thread, Runnable, sleep (), yield (), join (), synchronization I. Thread Overview

In an operating system, each independently executed program can be called a process, that is, a running process ". In the process, multiple execution units can be executed simultaneously. These execution units can be seen as a thread for program execution. A Java Runtime Environment is a single process that contains different classes and programs. A thread can be called a lightweight process. Threads require less resources to create and reside in the process, and can share resources in the process.

Ii. Thread Creation

1. Java provides two multi-threaded implementation methods: ① One inherits java. the Thread class under the lang Package rewrites the run () method of the Thread class, implements the code running on the Thread in the run () method, and provides a start () method is used to start a new thread. Example of creating an object: 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 (); // enable thread 5 while (true) {// print and output 6 System through an endless loop statement. out. println ("main () method running"); 7} 8} 9} 10 class MyThread extends Thread {11 public void run () {12 while (true) {13 System. out. println ("MyThread class run () method"); 14} 15} 16}
② A java. lang. Runnable interface is implemented, and the code running on the thread is also implemented in the run () method. A start () method is provided to start a new thread. Example of creating an object: 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 Thread = new thread (myThread); // create Thread object 5 thread. start (); // enable the thread and run () method 6 while (true) in the execution thread {// print and output 7 System through an endless loop statement. out. println ("main () method running"); 8} 9} 10} 11 class MyThread implements Runnable {12 public void run () {// code segment of the thread, when the start () method is called, the thread starts 13 while (true) {14 System. out. println ("MyThread class run () method"); 15} 16} 17}
2. Implementing the Runnable interface has the following advantages over inheriting the Thread class: ① It is suitable for multiple threads with the same program code to process the same resource, effectively separating threads from program code and data; ② this can avoid the limitations caused by java's single inheritance (a class cannot inherit the Thread class once it inherits a parent class ). 3. The so-called background thread refers to the thread that provides a general service in the background when the program is running, and this thread is not an indispensable part of the program. Therefore, when all non-Background threads end, the program will terminate and all background threads will be killed. Conversely, the program will not be terminated as long as any non-Background thread (User thread) is still running. The background thread terminates the run method without executing the finally clause. The subthread created by the background thread is also a background thread. When the setDaemon (true) Statement is called before a thread object is started (before the start () method), the thread becomes a background thread. Iii. Thread lifecycle and state transition

 

1. The new status (new) cannot be run at this time. It is only allocated memory by the Java Virtual Machine. 2. ready state (Runnable) when the thread object calls the start () method, the thread enters the ready state (also called the runable state), which is located in the running pool, now that the running conditions are met, you still need to wait for the system to schedule whether you can obtain the CPU usage right to start running. 3. The Running (Running) Ready thread obtains the CPU usage right and starts to execute the thread execution body in the run () method. The thread is in the Running state. Only a ready thread can be switched to the running state. 4. The blocking status (Blocked) is changed from the blocking status to the ready status: ① if the thread attempts to obtain the synchronization lock of an object, if the lock is held by other threads, the current thread enters the blocking state. If you want to enter the ready state from the blocking state, you must obtain the lock held by other threads. ② When the thread calls a blocking IO method, the thread will enter the blocking state. If you want to enter the ready state, you must wait until the blocked IO method is returned. ③ When the thread calls the wait () method of an object, it will also cause the thread to enter the blocking state. If you want to enter the ready state, you need to use the Y () method to wake up the thread. ④ When the Thread calls the Thread's sleep (long mills) method, it will also cause the Thread to enter the blocking state. In this case, you only need to wait until the Thread's sleep time is reached, the thread automatically enters the ready state. ⑤ When a thread calls the join () method of another thread, the current thread will be blocked. In this case, you must wait until the running of the newly added thread ends the blocking state and add it to the ready state. Note: The thread can only enter the ready state but not the running state. 5. When the Terminated thread run () finishes execution or the thread throws an uncaptured exception or error, the thread enters the dead state. Once the thread enters the dead state, it will no longer be eligible to run and cannot be switched to another State. 4. Thread Scheduling 1. thread priority each Java thread has a priority, which helps the operating system determine the thread scheduling sequence. The priority of a Java Thread is an integer. The value range is 1 (Thread. MIN_PRIORITY)-10 (Thread. MAX_PRIORITY ). For example: thread. setPriority (10); by default, each thread is assigned a normal priority of NORM_PRIORITY (5 ). Threads with a higher priority are more important to programs, and processor resources should be allocated before low-priority threads. However, the thread priority cannot guarantee the thread execution sequence and is very dependent on the platform. 2. Thread sleep Thread. sleep (long millis) method declaration throws an InerruptedException exception. Therefore, an exception should be caught or thrown when this method is called. This static method can only control the sleep of the current thread.
1 public class Example08 {2 public static void main (String [] args) throws Exception {3 // create a Thread 4 new Thread (new SleepThread ()). start (); 5 for (int I = 1; I <= 10; I ++) {6 if (I = 5) {7 Thread. sleep (2000); // The current thread sleeps for 2 seconds 8} 9 System. out. println ("the main Thread is outputting:" + I); 10 Thread. sleep (500); // The current thread sleep for 500 milliseconds 11} 12} 13} 14 class SleepThread implements Runnable {15 @ Override16 public void run () {17 for (int I = 1; I <= 10; I ++) {18 if (I = 3) {19 try {20 Thread. sleep (2000); 21} catch (InterruptedException e) {22 e. printStackTrace (); 23} 24} 25 System. out. println ("A Thread is being output:" + I); 26 try {27 Thread. sleep (500); 28} catch (Exception e) {29 e. printStackTrace (); 30} 31} 32
3. Thread concession the thread concession can be implemented through the yield () method. This method is similar to the sleep () method and can suspend the currently running thread. The difference is that yield () the method does not block the thread. It only converts the thread to the ready state and re-schedules the system scheduler. After a thread calls the yield () method, it can be executed only when the thread has the same or higher priority as the current thread.
1 // define YieldThread class to inherit Thread class 2 class YieldThread extends Thread {3 // define a construction method with parameters 4 public YieldThread (String name) {5 super (name ); // call the constructor of the parent class 6} 7 8 @ Override 9 public void run () {10 for (int I = 0; I <5; I ++) {11 System. out. println (Thread. currentThread (). getName () + "___" + I); 12 if (I = 3) {13 System. out. print ("Thread concession"); 14 Thread. yield (); // when the thread runs so far, 15} 16} 17} 18} 19 public class Example09 {20 public static void main (String [] args) {21 // create two threads 22 Thread t1 = new YieldThread ("Thread A"); 23 Thread t2 = new YieldThread ("Thread B "); 24 // enable two threads 25 t1.start (); 26 t2.start (); 27} 28 29}
4. Thread plug-in when a thread calls the join () method of another thread, the called thread will be blocked until it is joined () it will continue to run only after the thread added by the method is executed.
1 public class Example10 {2 public static void main (String [] args) throws Exception {3 // create Thread 4 Thread t = new Thread (new EemergencyThread (), "thread 1"); 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 join () method 10} 11 Thread. sleep (500); 12} 13} 14} 15 class EemergencyThread implements Runnable {16 @ Override17 public void run () {18 for (int I = 1; I <6; I ++) {19 System. out. println (Thread. currentThread (). getName () + "input:" + I); 20 try {21 Thread. sleep (500); 22} catch (InterruptedException e) {23 e. printStackTrace (); 24} 25} 26} 27}
5. multi-thread synchronization 1. synchronous code block: lock is a lock object. It is the key to synchronizing code blocks. It can be any type of objects, but the lock objects shared by multiple threads must be unique. "Arbitrary" refers to the type of the shared Lock Object. Synchronized (lock) {Share Resource code block Operation} 2. synchronization method:
Synchronized return value type method name ([parameter 1,...]) {}
3. synchronous code blocks and Synchronization Methods solve the thread security problem when multiple threads simultaneously access Shared data. As long as the same lock is added, only one thread can be executed at a time, however, when the thread executes the synchronization code, it will judge the lock status every time, which consumes resources and is less efficient. Example:
1 // define Ticket1 class to implement Runnable interface 2 class Ticket1 implements Runnable {3 private int tickets = 10; // define the variable tickets, assign a value of 10 4/* Synchronous Code block usage 5 Object lock = new Object (); // define any Object and use the lock 6 public void run () for Synchronous Code Blocks () {7 while (true) {8 synchronized (lock) {9 try {10 Thread. sleep (10); 11} catch (InterruptedException e) {12 e. printStackTrace (); 13} 14 if (tickets> 0) {15 System. out. println (Thread. currentThread (). getName () 16 + "--- sold tickets" + tickets --); 17} else {18 break; 19} 20} 21} 22 23} */24 25 public void run () {26 while (true) {27 saleTicket (); // call the ticket sales method 28 if (tickets <= 0) {29 break; 30} 31} 32 33} 34 // define a synchronization method saleTicket () 35 private synchronized void saleTicket () {36 if (tickets> 0) {37 try {38 Thread. sleep (10); 39} catch (InterruptedException e) {40 e. printStackTrace (); 41} 42 System. out. println (Thread. currentThread (). getName () + 43 "--- sold tickets" + tickets --); 44} 45} 46} 47 public class Example12 {48 public static void main (String [] args) {49 Ticket1 ticket = new Ticket1 (); 50 new Thread (ticket, "Thread 1 "). start (); 51 new Thread (ticket, "Thread 2 "). start (); 52 new Thread (ticket, "Thread 4 "). start (); 53 new Thread (ticket, "Thread 3 "). start (); 54} 55}
4. deadlock

A deadlock occurs when multiple threads are blocked at the same time, and one or all of them are waiting for the release of a resource. The program cannot be terminated because the thread is blocked indefinitely.

Four Conditions for java deadlock:

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

② Cannot be preemptible. Resource requestors cannot forcibly seize resources from the resource Occupation List. resources can only be released by the resource Occupation List.

③ Request and Retention: when the resource requestor requests other resources, it maintains its possession of the original resources.

④ Cyclic waiting: there is a waiting queue: P1 occupies P2 resources, P2 occupies P3 resources, and P3 occupies P1 resources. This forms a wait loop.

6. multi-thread communication provides the wait (), Y (), and notifyAll () methods in the Object class to solve the thread communication problem, that is, let the thread execute in turn in a certain order. Method to wake up a thread:
Method Declaration Function Description
Void wait () Causes the current thread to discard the synchronization lock and wait until other threads enter the synchronization lock, and calls the Y () method or the yyall () method to wake up the thread.
Void notify () Wake up the first thread that calls the wait () method for this synchronization lock wait
Void policyall () Wake up all threads that call the wait () method for this synchronization lock
The callers of wait (), Y (), and notifyAll () methods should be synchronization lock objects. If the callers of the three methods are not synchronization lock objects, the Java Virtual Machine will throw IllegalMonitorStateException. Sample Data Access:
1 class Storage {2 private int [] cells = new int [10]; // array Storage array 3 private int inPos, outPos; // inPos indicates the subscript of the group when it is stored, outPos indicates the group subscript 4 private int count; // number of data stored or retrieved 5 public synchronized void put (int num) {// defines a put () method To save data to the array 6 try {7 // If the put data is equal to the length of cells, this thread waits for 8 while (count = cells. length) {9 this. wait (); 10} 11 cells [inPos] = num; // Add 12 System data to the array. out. println ("cells [" + inPos + "] Put data ---" + cells [inPos]); 13 inPos ++; // Add 114 if (inPos = cells. length) 15 inPos = 0; // when inPos is an array with a length of 10, set it to 016 count ++; 17 this. notify (); 18} catch (Exception e) {19 e. printStackTrace (); 20} 21} 22 // define a get () method to retrieve data from the array 23 public synchronized void get () {24 try {25 while (count = 0) {26 this. wait (); 27} 28 int data = cells [outPos]; 29 System. out. println ("retrieve data from cells [" + outPos + "]" + data); 30 cells [outPos] = 0; // After extracting, the current data is set to zero 31 outPos ++; // After the element is obtained, add 132 if (outPos = cells. length) 33 outPos = 0; 34 count --; // each time an element is taken out, count minus 135 this. notify (); 36} catch (Exception e) {37 e. printStackTrace (); 38} 39} 40} 41 class Input implements Runnable {// Input Thread class 42 private Storage st; 43 private int num; // define a variable num44 Input (Storage st) {// receives a Storage object by constructor 45 this. st = st; 46} 47 public void run () {48 while (true) {49 st. put (num ++); // save num to an array, after each Storage, num is automatically increased by 50} 51} 52} 53 class Output implements Runnable {// Output Thread class 54 private Storage st; 55 Output (Storage st) {// receives a Storage object 56 this through the constructor. st = st; 57} 58 public void run () {59 while (true) {60 st. get (); // cyclically retrieve element 61} 62} 63} 64 public class Example17 {65 public static void main (String [] args) {66 Storage st = new Storage (); // create an Array Storage Class Object 67 Input input = new Input (st ); // create an Input object to pass in the Storage object 68 Output output = new Output (st); // create an Output object to pass in the Storage object 69 new Thread (input ). start (); // enable new Thread 70 new Thread (output ). start (); // enable new thread 71 72} 73}

Running result

Put data in cells [1] --- 214311 cells [2] Put data --- 214312 cells [3] Put data --- 214313 cells [4] Put data --- 214314 cells [5] put data in --- 214315 cells [6] Put data --- 214316 cells [7] Put data --- 214317 cells [8] Put data --- 214318 cells [9] Put data --- 214319 cells [0] Put data --- 214320 get data from cells [1] 214311 get data from cells [2] 214312 get data from cells [3] 214313 get data from cells [3 [4] Fetch data 214314 retrieve data from cells [5] 214315 retrieve data from cells [6] 214316 retrieve data from cells [7] 214317 retrieve data from cells [8] data 214318 retrieve data from cells [9] 214319 retrieve data from cells [0] 214320

Example of multi-thread accumulation:

Simulate 10 threads, add the first thread from 1 to 10, and add the second thread from 11 to 20 ..... add the tenth thread from 91 to 100, and then add the results of the 10 threads.

 1 public class Accumulator extends Thread { 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     public void run() {11         int sum = 0;12         for (int i = 0; i < 10; i++) {13             sum += stratNum + i;14         }15          add(sum); 16     }17     public static void main(String[] args) throws Exception {18         Thread[] threadList = new Thread[10];19         for (int i = 0; i < 10; i++) {20             threadList[i] = new Accumulator(10 * i + 1);21             threadList[i].start();22         }23         for (int i = 0; i < 10; i++) {24             threadList[i].join();25         }26                 System.out.println("Sum is : " + sum);27     }28 }

 

Related Article

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.