Dark Horse programmer ---- java multithreading and synchronization mechanism, java Multithreading
------ <A href = "http://www.itheima.com" target = "blank"> Java training, Android training, iOS training,. Net training </a>, look forward to communicating with you! -------
1. Understand the concepts of programs, processes, and threads
A program can be understood as a static code, a set of computer commands, which are stored on a disk as files.
A process can be understood as a program in execution. A single program opens a separate address space for separate work.
A thread can be understood as a further subdivision of the process, and an execution path of the program.
Multithreading does not mean that many threads run at the same time, but rather a fast switch between CPUs.
Threads are roughly divided into five states:
Create a new Thread and its subclass
The running thread occupies the cpu.
Blocking has execution qualification, but does not get the cpu. This is a random cpu decision.
Frozen, unexecuted, in sleep state
Execution of the run method of the dead end is completed (before 1.5, the stop method can be called to force the end thread)
The Thread is actually created by Windows, and java has encapsulated the Thread creation function. You only need to use it to inherit the Thread class in the java. lang package. There are roughly two methods
Method 1: directly inherit the Thread class
Class PrintNum extends Thread {// inherits the Thread class public void run () {// re-write run method, code executed by the sub-Thread for (int I = 1; I <= 100; I ++) {if (I % 2 = 0) {System. out. println (Thread. currentThread (). getName () + ":" + I) ;}} public PrintNum (String name) {super (name );}} public class TestThread {public static void main (String [] args) {PrintNum p1 = new PrintNum ("thread 1"); PrintNum p2 = new PrintNum ("thread 2 "); p1.setPriority (Thread. MAX_PRIORITY); // The priority is 10p2. setPriority (Thread. MIN_PRIORITY); // priority 1p1. start (); // start the thread and call the run method p2.start ();}}
There are three steps: 1. Create a thread. 2. Rewrite the run method in Tread. Put the code block to be executed. 3. Call the stat method, start the thread, and call the run method.
Method 2: implement the Runnable interface
Class SubThread implements Runnable {public void run () {// 2. re-write the run method // code executed by the sub-thread for (int I = 1; I <= 100; I ++) {if (I % 2 = 0) {System. out. println (Thread. currentThread (). getName () + ":" + I) ;}}} public class TestThread {public static void main (String [] args) {SubThread s = new SubThread (); thread t1 = new Thread (s); // 1. create Thread t2 = new Thread (s); t1.setName ("Thread 1"); t2.setName ("Thread 2"); t1.start (); // 3. start and call the run method t2.start ();}}
Comparison of the two methods:
If this class does not inherit other classes, use the inheritance method. The run method is written in the Thread class, in addition, for a large segment of code that has appeared for multiple cycles, the anonymous internal class is also directly used to package it for multi-thread implementation, which is relatively simple.
new Thread(){ public void run(){ for(int i=0;i<100;i++){ System.out.println(i); } } }.start();
However, single inheritance has limitations. If multiple threads share data, we recommend that you use the implementation method. At the same time, the class of shared data can be used as the implementation class of the Runnable interface, the run method is written in the Runnable interface. For example, you can buy 100 tickets at the same time in two windows.
Class gxzy implements Runnable {// implement the Runnable interface private int piao = 100; public void run () {// override the run method while (true) {if (piao> 0) System. out. println (Thread. currentThread (). getName () + "" + piao -- + "") ;}} public class maipiao {public static void main (String [] args) {gxzy gx = new gxzy (); Thread xz1 = new Thread (gx); // create Thread xz2 = new Thread (gx ); xz1.setName ("1st ticket window"); xz2.setName ("2nd ticket window"); xz1.start (); // start the thread and call the run method xz2.start ();}}
However, the preceding program has a security problem, that is, if the online program has not run the output statement under the if statement, the cpu is occupied by other programs, the thread is in the blocking state, while other threads are behind. When the thread returns to the running state, the last ticket is sold, it is possible that the following thread will sell 0th tickets. Write a sleep method to clearly see the problem.
Class gxzy implements Runnable {private int piao = 100; Object obj = new Object (); public void run () {while (true) {if (piao> 0) try {Thread. sleep (3); // stop for 3 ms} catch (Exception e) {} System. out. println (Thread. currentThread (). getName () + "" + piao -- + "");}}}
At this time, we need to adopt synchronization to solve the problem. Synchronization provides a lock. When the thread executes the run method, the lock will be closed, and other threads will not be able to enter the lock, other threads will not be able to come in until the thread finishes executing the lock.
The synchronized keyword is synchronization. There are two ways to write the synchronous code block. The lock in it can be any object. Generally, the object class or the existing resource class is used.
Synchronized (object) {executed code block}
Another method is to use synchronized to modify a function called a synchronous function, that is, to write the code block to be synchronized separately in a method, and then use synchronized to modify it. The lock here is this. If the function is modified by static, because this cannot exist in the static state before the object, its lock is java. class bytecode file object in the format of class name. class.
Whether it is a synchronous code block or a Synchronous Code function, there are two or more threads that use the same lock.
Take a look at the lazy style in singleton mode and solve his thread problems with synchronization.
Class aa {private static aa bb = null; private aa () {} public static aa lei () {if (bb = null); // double judgment, improve Efficiency synchronized (aa. class) {// after an object is created, access from all threads will be denied if (bb = null) {bb = new aa () ;}return bb ;}}}
We use code blocks instead of synchronous functions. This is more flexible. If we use synchronous functions directly, it will be very inefficient. Even when an object is created, there will be threads coming in to access the lock, one drawback of the lock is that it consumes resources. The use of the code block uses double judgment. If you make a judgment before the lock, you do not need to access the lock. It is worth noting that the function that returns the object is static, and the static lock is the class name. class.