The second article in the dark horse programmer series is multithreading (2) and the second article in the dark horse Series

Source: Internet
Author: User

The second article in the dark horse programmer series is multithreading (2) and the second article in the dark horse Series

ASP. Net + Android + IOS development and Net training. We look forward to communicating with you!

 

(This article is based on the course video of teacher Bi Xiangdong, if you want to learn in detail, please watch the video of teacher Bi Baidu Network Disk link address: http://pan.baidu.com/s/1i3m6DrJ)

 

Directory: 1. Thread communication-Example of the production consumer (thread communication security, waiting for wake-up mechanism) 2. Stop the thread, its problems, and solutions3. Daemon threads and several Thread Methods4. common thread writing

1. Thread communication-Example of a production consumer

Sample Code:

1 public class ProducerConsumer {2 // requirement: the production and consumption behaviors are performed in sequence. Set the three public static void main (String [] args) {4 5 Product pro = new Product () for each producer and consumer thread of the Product for BMW (); 6 7 new Thread (new Producter (pro )). start (); 8 new Thread (new Consumer (pro )). start (); 9 new Thread (new Producter (pro )). start (); 10 new Thread (new Consumer (pro )). start (); 11 12} 13} 14 class Product {15 16 private String name; 17 private int No = 1; 18 boolean flag = false; 19 20 public synchronized void set (Stri Ng names) {21 while (flag) 22 try {23 this. wait (); // wait Status 24} catch (InterruptedException e) {25 e. printStackTrace (); 26} 27 this. name = names + "---" + this. no ++; 28 System. out. println (this. name + "---" + Thread. currentThread (). getName () + "production"); 29 flag = true; 30 this. notifyAll (); // wake up all threads 31} 32 public synchronized void out () {33 while (! Flag) 34 try {35 this. wait (); // wait Status 36} catch (InterruptedException e) {37 e. printStackTrace (); 38} 39 System. out. println (this. name + "---" + Thread. currentThread (). getName () + "consumed -------"); 40 flag = false; 41 this. notifyAll (); // wake up all threads 42} 43} 44 // producer 45 class Producter implements Runnable {46 private Product p; 47 public Producter (Product pr) {48 this. p = pr; 49} 50 public void run () {51 while (true) {52 p. set ("BMW"); 53} 54} 55} 56 // Consumer 57 class Consumer implements Runnable {58 private Product p; 59 public Consumer (Product pr) {60 this. p = pr; 61} 62 public void run () {63 while (true) {64 p. out (); 65} 66} 67}View Code

 

 

Improved code using the new JDK5.0 feature

1/* after JDK5.0, the Lock and Condition features are added to replace the tedious synchronization and Lock operations */2 public class ProducerConsumerNew {3 4 public static void main (String [] args) {5 6 Product pro = new Product (); 7 8 new Thread (new Producter (pro )). start (); 9 new Thread (new Consumer (pro )). start (); 10 new Thread (new Producter (pro )). start (); 11 new Thread (new Consumer (pro )). start (); 12 13} 14 15} 16 class ProductNew {17 private String name; 18 private in T No = 1; 19 boolean flag = false; 20 21 private Lock lock = new ReentrantLock (); 22 private Condition con1 = lock. newCondition (); 23 private Condition con2 = lock. newCondition (); 24 25 public void set (String name) {26 27 while (flag) 28 try {29 lock. lock (); 30 con1.wait (); 31} catch (InterruptedException e) {32 e. printStackTrace (); 33} finally {34 lock. unlock (); 35} 36 this. name = name + "---" + this. no ++; 37 System. out. pri Ntln (this. name + "---" + Thread. currentThread (). getName () + "production"); 38 39 this. flag = true; 40 con2.signal (); 41} 42 43 public void out () {44 while (! This. flag) 45 try {46 lock. lock (); 47 con2.wait (); 48} catch (InterruptedException e) {49 e. printStackTrace (); 50} finally {51 lock. unlock (); 52 con1.signal (); 53} 54 System. out. println (this. name + "---" + Thread. currentThread (). getName () + "consumed -------"); 55 56 this. flag = false; 57} 58} 59 // producer 60 class ProducterNew implements Runnable {61 private ProductNew p; 62 public ProducterNew (ProductNew pr) {63 this. p = pr; 64} 65 public void run () {66 while (true) {67 p. set ("BMW"); 68} 69} 70} 71 // consumer 72 class ConsumerNew implements Runnable {73 private ProductNew p; 74 public ConsumerNew (ProductNew pr) {75 this. p = pr; 76} 77 public void run () {78 while (true) 79 p. out (); 80} 81}View Code

 

2. Stop the thread and Its Problems and Solutions

Thread stop idea: To enable multi-threaded running, the running code is usually a loop structure. As long as the loop is controlled, the run () method can end, And the thread ends.

Special Cases: When the thread is frozen (wait (), it will not read the mark, and the thread will not end.

Solution: When there is no specified method to restore the frozen thread to the running state, you need to use the Interrupt () method to forcibly clear the frozen state, and then use the operation mark to end the thread

 

A simple code example

1 public class ThreadStop {2 3 public static void main (String [] args) {4 5 ThreadTt tt = new ThreadTt (); 6 7 Thread th1 = new Thread (tt ); 8 Thread Th1 = new Thread (tt); 9 th1.start (); 10 th2.start (); 11 int count = 0; 12 while (true) {13 if (++ count> 60) {// loop to control the end of a thread 14 th1.interrupt (); // force clear the thread freeze status 15 th2.interrupt (); 16 break; 17} 18 System. out. println (Thread. currentThread (). getName () + ".... run --- "+ count); 19} 20 System. out. println (Thread. currentThread (). getName () + ".... over "); 21} 22} 23 class ThreadTt implements Runnable {24 25 boolean flag = true; 26 Lock lock = new ReentrantLock (); 27 Condition con = lock. newCondition (); 28 public synchronized void run () {29 30 while (flag) {31 try {32 wait (); // use this method to make the thread in the frozen state 33} catch (InterruptedException e) {34 System. out. println (e. getStackTrace (); 35 flag = false; 36} 37 System. out. println (Thread. currentThread (). getName () + "... run "); 38} 39} 40}View Code

 

 

 

3. Daemon threads and several Thread Methods

 

Daemon thread/user thread: Generally speaking, it is a "background process". When the current processes are all over, the background process automatically ends. When the running threads are all daemon threads, the JVM automatically exits.

 

SetDaemon ()Method To set the daemon thread. This method must be called before the thread is started.

 

 

Join ()Method features: When thread A executes the jion () method of thread B, thread A will wait and wait until all thread B is executed. Jion can be used to temporarily join the thread execution thread to snatch the cpu execution right

 

ToString ()Method

 

SetPriority ()Method To change the priority of a thread. Priority indicates the frequency of resource grabbing.

 

Yield ()Method to pause the execution of the current thread and execute other threads

 

4. common thread writing methods (internal classes are used)

Read the code.

 

1 public class ThreadStand {2 3 public static void main (String [] args) {4 // common method of multithreading in work, build internal class 5 new Thread () {6 public void run () {7 for (int I = 0; I <100; I ++) 8 System. out. println (Thread. currentThread (). getName () + ".... run .... "+ I); 9} 10 }. start (); 11 12 for (int I = 0; I <100; I ++) 13 System. out. println (Thread. currentThread (). getName () + ".... run .... "+ I); 14 15 // construct the internal class 16 Runnable rn = new Runnable () {17 public void run () {18 for (int I = 0; I <100; I ++) 19 System. out. println (Thread. currentThread (). getName () + ".... run .... "+ I); 20} 21}; 22 new Thread (rn ). start (); 23} 24}View Code

 

 

 

Errors are inevitable for beginners. You are welcome to judge and continue to correct ing ...........

 

ASP. Net + Android + IOS development and Net training. We look forward to communicating with you!

 

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.