Java thread summary, Java thread Summary
This article briefly introduces thread-related knowledge in the Java World. It mainly includes thread creation and destruction, thread security and synchronization, and thread communication. Note that there is no deep new knowledge in this article, only because some time ago when I looked at the project code, I found that some people have many misunderstandings about this, so I will sort it out here to help similar students and watch myself out.
1. Thread creation and destruction;
A) To create a Thread, You can inherit the Thread class or implement the Runnable interface, and override the run () method. The run () method is the content that the Thread needs to execute.
B). The Runnable interface and Thread implementation are more flexible than inheriting the Thread separately. You can share a Runnable interface instance to share resources in the Thread.
C ). thread destruction is not recommended. stop () method. If this method is improperly used, deadlocks may occur. In more cases, we recommend that you end this method by using additional variables (or conditions) in the run () method.
2. thread security and synchronization;
A) For code segments that require ACID atomic consistency, you can use synchronized (lockKey) {} to lock them;
B) at the same time, the synchronized keyword can be used to modify a method, indicating that the entire method must follow ACID atomic consistency. It is worth noting that the lockKey is equivalent to the this keyword;
B) we recommend that you make a necessary condition judgment in the locked code block.
3. thread communication can be completed by using the wait () notify () notifyAll () methods in the java World. These three methods are defined in the Object class, therefore, all objects can be used.
4. The following code snippets are used to describe
A) Demonstrate thread creation and destruction, and thread security and Synchronization
1 public class ThreadTest implements Runnable {2 private boolean stop; // whether to stop running 3 private int tiketCount = 100000; // total number of votes 4 private boolean lockTypeIsMethod = true; // whether the method lock or code block 5 6 public boolean isStop () {7 return stop; 8} 9 public void setStop (boolean stop) {10 this. stop = stop; 11} 12 13 public boolean isLockTypeMethod () {14 return lockTypeIsMethod; 15} 16 public void setLockTypeIsMethod (Boolean lockTypeIsMethod) {17 this. lockTypeIsMethod = lockTypeIsMethod; 18} 19 20 @ Override21 public void run () {22 while (tiketCount> 0 &&! Stop) {23 try {24 Thread. sleep (50); // latency for demonstration 25} catch (InterruptedException e) {26 e. printStackTrace (); 27} 28 29 // if the method is locked by 30 if (lockTypeIsMethod) {31 sale (); 32} else {33 synchronized (this) {34 if (tiketCount> 0 &&! Stop) {35 System. out. println ("Block lock: threadId =" 36 + Thread. currentThread (). getName () + ", ticketNO:" + tiketCount --); 37} 38} 39} 40} 41} 42 43 public synchronized void sale () {44 if (tiketCount> 0 &&! Stop) {45 System. out. println ("usage lock: threadId =" 46 + Thread. currentThread (). getName () + ", ticketNO:" + tiketCount --); 47} 48} 49}Thread definition class
1 public static void main (String [] args) throws InterruptedException {2 ThreadTest threadTest = new ThreadTest (); // share variable ThreadTest 3 // enable four threads 4 new Thread (threadTest ). start (); 5 new Thread (threadTest ). start (); 6 new Thread (threadTest ). start (); 7 new Thread (threadTest ). start (); 8 // simulate the sharing variable, 9 // 1. use the method body and code block alternately for Thread Synchronization Experiment 10 // 2. the simulated Thread stops 11 for (int I = 0; I <100; I ++) {12 Thread. sleep (1000); 13 threadTest. setLockTypeIsMethod (I % 2 = 0); 14 if (I = 50) {15 threadTest. setStop (true); 16} 17} 18}Caller
B ). demonstrate thread communication. In this example, two threads are simulated to read and write a set using the production and consumer roles. When there is data in the Set, the consumer is notified to process the data, after processing, the producer is notified to put data into the collection.
1 // data Warehouse 2 public class DataRepository {3 private List <String> data = new ArrayList <> (); 4 private boolean hasData; 5 6 public boolean HasData () {7 return hasData; 8} 9 10 public void setHasData (boolean hasData) {11 this. hasData = hasData; 12} 13 14 // put data 15 public synchronized void put (List <String> data) throws InterruptedException {16 // when the producer puts data, if there is still data, wait. 17 if (hasData) {18 wait (); 19} 20 thi S. data = data; 21 hasData = true; 22 // notify the consumer 23 notify (); 24} 25 26 // read data 27 public synchronized List <String> get () throws InterruptedException {28 // wait for 29 if (! HasData) {30 wait (); 31} 32 // returns 33 List <String> rs = new ArrayList <> (data); 34 data. clear (); 35 hasData = false; 36 notify (); 37 return rs; 38} 39}Data Warehouse 1 public class Producer implements Runnable {2 private DataRepository dataRepository; // Data Warehouse 3 public Producer (DataRepository dataRepository) {4 this. dataRepository = dataRepository; 5} 6 7 public void run () {8 while (true) {9 try {10 Thread. sleep (1000); 11} catch (InterruptedException e) {12 e. printStackTrace (); 13} 14 List <String> temp = new ArrayList <> (); 15 temp. add ("------------"); 16 temp. add ("First Data"); 17 temp. add ("second data"); 18 temp. add ("third data"); 19 temp. add ("fourth data"); 20 temp. add ("------------"); 21 try {22 dataRepository. put (temp); 23} catch (InterruptedException e) {24 e. printStackTrace (); 25} 26} 27} 28}Producer 1 public class Consumer implements Runnable {2 private DataRepository dataRepository; 3 4 public Consumer (DataRepository dataRepository) {5 this. dataRepository = dataRepository; 6} 7 8 public void run () {9 while (true) {10 try {11 Thread. sleep (1000); 12} catch (InterruptedException e) {13 e. printStackTrace (); 14} 15 try {16 List <String> data = dataRepository. get (); 17 if (data! = Null &&! Data. isEmpty () {18 for (String temp: data) {19 System. out. println (temp); 20} 21} 22} catch (InterruptedException e) {23 e. printStackTrace (); 24} 25} 26} 27}Consumer 1 public class Client {2 public static void main (String [] args) throws InterruptedException {3 4 DataRepository dr = new DataRepository (); 5 new Thread (new Producer (dr )). start (); // start producer Thread 6 new Thread (new Consumer (dr )). start (); // start consumer thread 7} 8}Caller
Postscript:
A) multithreading is a basic knowledge. First of all, we need to understand its most basic concepts to be able to easily use it in projects;
B) the theoretical support required by whatever language is similar;
C ). back to the original concept, in multithreading, do not use threads to communicate with each other, or use threads to synchronize without synchronization, try not to use multithreading if you don't use multithreading. It's a bit vague.