02. Java multi-thread concurrent library API usage, 02. java multi-thread library api

Source: Internet
Author: User

02. Java multi-thread concurrent library API usage, 02. java multi-thread library api
1. Review of traditional Thread Technology

What is the difference between the inherited thread and Runnable? Why do so many people adopt the second approach?

Because the second method is more in line with the object-oriented way of thinking. To create a thread, the thread needs to run the code, and the running code is encapsulated into an independent object. One is called a thread, and the other is called a thread running Code. These are two things. The combination of the two things demonstrates the object-oriented thinking. If two threads implement data sharing, Runnable must be used.

Check the source code of the run () method of the Thread class. We can see that both methods are actually calling the run method of the Thread object. If the run method of the Thread class is not overwritten, a Runnable object is set for the Thread object. The run method calls the run method of the Runnable object.

Problem: If the run code is written in the run method covered by the Thread subclass and a Runnable object is passed to the Thread subclass object, when the thread is running, is the Execution Code of the sub-class run method? Or the code of the run method of the Runnable object? The run method of the subclass.

Sample Code

 

 1     new Thread(new Runnable() { 2         public void run() { 3             while (true) { 4                 System.out.println("run:runnable"); 5             } 6         } 7     }) { 8         public void run() { 9             while (true) {10                 try {11                     Thread.sleep(1000);12                 } catch (Exception e) {13                 }14                 System.out.println("run:thread");15             }16         }17     }.start();

 

This Thread runs the run method in the rewritten Thread instead of the run method in Runnable, because the run method in the traditional Thread is:

1     public void run() {2         if (target != null) {3             target.run();4         }   5     }

 

If you want to run the run method in Runnable, you must call it in Thread, but now I overwrite the run method in Thread, resulting in if (target! = Null) {target. run ();} does not exist, so the run method in Runnable cannot be called.

Note: Does multi-threaded execution increase the program running efficiency? Why is there multi-thread download?

No, sometimes it will reduce the program running efficiency. Because there is only one CPU, the time may be delayed during CPU context switching.

Multi-thread download: in fact, your machine is not getting faster, but you have snatched the server bandwidth. If you download it by yourself and the server provides 20 K for you, the server provides 200 K for 10 people. At this time, you snatched 200 k, so it felt faster.

2. Review of traditional Timer technology (before jdk1.5) Timer and TimerTask

Timer: a tool used by a thread to schedule tasks to be executed in a background thread. You can schedule the task to be executed once, or perform the task repeatedly on a regular basis.

ScheduleAtFixedRate (TimerTask task, Date firstTime, long period ):

Schedule the specified task to start repeating at a fixed rate at a specified time.

Schedule (TimerTask task, long delay, long period): schedule the specified task to start repeated fixed delay execution after the specified delay.

Job Scheduling framework Quartz (a tool dedicated to processing time and time ). You can use it to create simple or complex scheduling for executing a job. {Http://www.oschina.net/p/quartz}

Question: Send a newspaper at every morning.

Q: I go to work from Monday to Friday every week, but do not go to work on Sunday on Saturday.

Sample Code: (execute different events at different intervals)

1 package com. chunjiangchao. thread; 2 3 import java. util. timer; 4 import java. util. timerTask; 5/** 6 * repeats a task, however, the time interval is different from the status of * @ author chunjiangchao 8*9 */10 public class TimerDemo02 {11 12 private static long count = 1; 13 public static void main (String [] args) {14 Timer timer = new Timer (); 15 timer. schedule (new Task (), 1000); 16/* 17: The result of the test is as follows: 18: The Task is executed. The current time is 146061323119: 146061323520: The Task is executed, the current time is 146061323721. The current time is 146061324122 */23 24 new Thread (new Runnable () {25 public void run () {26 while (true) {27 System. out. println ("run: runnable"); 28} 29} 30}) {31 public void run () {32 while (true) {33 try {34 Thread. sleep (1000); 35} catch (Exception e) {36} 37 System. out. println ("run: thread"); 38} 39} 40 }. start (); 41 42 43} 44 45 static class Task extends TimerTask {46 47 @ Override48 public void run () {49 System. out. println ("Run the task, current time:" + System. currentTimeMillis ()/1000); 50 new Timer (). schedule (new Task (), 2000*(1 + count % 2); 51 count ++; 52} 53 54} 55 56}

 

3. Traditional thread mutex Technology

This example: the key lies in the description: to achieve mutual exclusion between threads, the number of threads must reach two or more. At the same time, the same lock must be used to access resources (this is required ). If both threads access different synchronization code blocks and their lock objects are different, these threads will not achieve synchronization.

Sample Code: (access to the same resource object, but the Lock Object is different, the same does not achieve the purpose of synchronization)

1 package com. chunjiangchao. thread; 2/** 3 * synchronization and mutual exclusion between threads 4 * @ author chunjiangchao 5 * because the print1 method and the print3 method Lock Object are the same, so when calling, the lock of print2 is the object that is currently executing the print2 method, and 6 * is executed simultaneously with print1 and print3, the printed result is not the expected result 7*8 */9 public class TraditionalThreadSynchronizedDemo {10 11 public static void main (String [] args) {12 final MyPrint myPrint = new MyPrint (); 13 // A14 new Thread (new Runnable () {15 16 @ Override17 public void run () {18 myPrint. print1 ("chunjiangchao"); 19} 20 }). start (); 21 // B22 // new Thread (new Runnable () {23 // 24 // @ Override25 // public void run () {26 // myPrint. print2 ("fengbianyun"); 27 //} 28 //}). start (); 29 // C30 new Thread (new Runnable () {31 32 @ Override33 public void run () {34 myPrint. print3 ("liushaoyue"); 35} 36 }). start (); 37} 38 static class MyPrint {39 public void print1 (String str) {40 synchronized (MyPrint. class) {41 for (char c: str. toCharArray () {42 System. out. print (c); 43 ps leep (200); 44} 45 System. out. println ("print1 has been printed"); 46} 47 48} 49 public synchronized void print2 (String str) {50 for (char c: str. toCharArray () {51 System. out. print (c); 52 ps leep (200); 53} 54 System. out. println ("print2 has been printed"); 55} 56 public synchronized static void print3 (String str) {57 for (char c: str. toCharArray () {58 System. out. print (c); 59 pSleep (200); 60} 61 System. out. println ("print3 has been printed"); 62} 63 private static void pSleep (long time) {64 try {65 Thread. sleep (time); 66} catch (InterruptedException e) {67 e. printStackTrace (); 68} 69} 70 71} 72 73}View Code

 

4. Traditional thread synchronous communication technology

During the design, it is best to encapsulate the relevant code into a class, which not only facilitates processing, but also achieves Internal High coupling.

Problem example

 

Experience: several methods that need to use common data (including synchronization locks) or common algorithms should be applied to the same class. This design exactly reflects the high class clustering and program robustness.

For synchronous communication, the problem of mutex is not written on the thread, but directly written in the resource. The thread can be used directly. The advantage is that my class will be handed over to any thread for access in the future, and it will naturally be synchronized without considering the thread synchronization issue. If it is written on the thread, and tomorrow there will be a third thread to call me, you have to write mutex write synchronization on the third thread. (Write all in the resource class, rather than in the thread code)

Sample Code: (the Sub-thread loops 10 times, then the main thread loops 100, and then returns to the sub-thread loop 10 times, and then returns to the main thread and loops 100 again, so the loop is 50 times, write the program .)

1 package com. chunjiangchao. thread; 2 3 public class TraditionalThreadCommunication {4/*** 5 * experience: Related to thread mutual exclusion and sharing, you should think of writing the synchronization method in the resource, instead of writing it in the thread code block to determine the mark in the resource, it is best to use the while Statement 6 */7 public static void main (String [] args) {8 final Output output = new Output (); 9 new Thread (new Runnable () {10 public void run () {11 for (int I = 0; I <50; I ++) {12 output. sub (10); 13} 14} 15 }). start (); 16 for (int I = 0; I <50; I ++) {17 output. main (I); 18} 19} 20} 21 22 class Output {23 private boolean flag = true; 24 25 public synchronized void sub (int I) {26 while (! Flag) {// use while is more robust than use if, because even if the thread is awakened, it can also determine whether it really needs to execute 27 // to prevent the occurrence of pseudo-wake events. 28 try {29 this. wait (); 30} catch (InterruptedException e) {31} 32} 33 for (int j = 0; j <10; j ++) {34 System. out. println (I + "sub-thread running" + j); 35} 36 flag = false; // remember to change the flag status 37 this. Y (); // Finally, wake up other threads that want to use the lock 38} 39 40 public synchronized void main (int I) {41 while (flag) {42 try {43 this. wait (); 44} catch (InterruptedException e) {45} 46} 47 for (int j = 0; j <100; j ++) {48 System. out. println (I + "main thread running" + j); 49} 50 flag = true; 51 this. notify (); 52} 53}

 

5. Concepts and functions of shared variables within the thread range

Data sharing within the thread range: whether it is module A or Module B, if they are running on the same thread, the data they operate on should be the same. The data in each thread is the same regardless of the thread on which module A and Module B run. (Data on the respective threads should be independent)

Transaction Processing between threads:

The following error cannot occur: the data transferred from thread1 is not in time. The CPU time slice is transferred to thread2, which is used for execution. The CPU time slice is transferred to thread2, transferred out, and finally submitted directly. The thread1 data is incorrect.

What are the functions of variables within the thread range?

I have done this transaction within the thread scope, and do not affect the transactions of other threads. However, in my thread, several modules are independent, and these modules need to share the same object. They must be shared and independent, shared within the thread, and independent outside the thread. [For the same program code, multiple modules must share one copy of data when running in the same thread, and another copy of data when running in another thread .]

Sample Code (different threads share the same Map object, but each element in the Map represents data of different threads)

1 package com. chunjiangchao. thread; 2 3 import java. util. hashMap; 4 import java. util. map; 5 import java. util. random; 6 7/** 8 * data sharing within the thread range 9 * @ author chunjiangchao10 * 11 */12 public class ThreadScopeShareDataDemo {13/All threads share data as datas, however, the key of each element in datas is Thread, and each element is independent for each Thread. value represents the data processed by different threads. 14 private static Map <Thread, integer> datas = new HashMap <Thread, Integer> (); 15 public static void main (String [] args) {16 for (int I = 0; I <2; I ++) {17 new Thread (new Runnable () {18 19 @ Override20 public void run () {21 int nextInt = new Random (). nextInt (); 22 datas. put (Thread. currentThread (), nextInt); 23 // module A is independent of Module B, but module A and Module B share the data in the current thread 24 new ModuleA (). getThreadData (); 25 new ModuleB (). getThreadData (); 26} 27 }). start (); 28} 29/* 30 print the result as 31 Thread-1 ModuleA get the variable:-91804979332 Thread-0 ModuleA get the variable is: -142485314833 ModuleB of Thread-0 obtains the following variables:-142485314834 ModuleB of Thread-1: -91804979335 36 */37} 38 static class ModuleA {39 public void getThreadData () {40 System. out. println (Thread. currentThread (). the variable obtained by getName () + "ModuleA is:" + datas. get (Thread. currentThread (); 41} 42} 43 static class ModuleB {44 public void getThreadData () {45 System. out. println (Thread. currentThread (). the variable obtained by getName () + "ModuleB is:" + datas. get (Thread. currentThread (); 46} 47} 48 49}
6. ThreadLocal class and application skills

ThreadLocal is equivalent to a Map.

A ThreadLocal represents a variable, so only one data can be put. If you have two variables to be shared within the thread range, you need to define two ThreadLocal objects, if there is a one hundred variable to be shared by the thread? Then we should define an object to hold one hundred variables, and then store this object in ThreadLocal.

Q: How can I get a notification when the thread ends? Tip: the VM is listened.

The most important thing is the design method involved.

 

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.