Multithreading-basic operations and basic operations

Source: Internet
Author: User

Multithreading-basic operations and basic operations
What is multithreading:

Process: A running program, QQ 360 ......

Thread: The execution path of an execution program in the process. A program must have at least one execution path. (If the antivirus computer in 360 is cleaned and running at the same time, multiple paths must be enabled)

Each thread has its own content to run, which can be called a task to be executed by a thread.

Multithreading is enabled to run multiple pieces of code at the same time.

Benefits: solved the problem of multiple concurrent operations.

Disadvantages: too many threads will lead to low efficiency (because the execution of the program is completed by random and fast switching of the CPU)

When JVM is started, multiple threads are started.

During multi-threaded running, if a thread throws an exception, the thread stops running (out of stack), but does not affect the normal operation of other threads.

Four States of a thread:

Creation thread:

Method 1: Inherit the Thread class

Method 2: implement the Runnable interface

Analysis: the purpose of creating a thread is to open up an execution path so that the thread can run the Specified Code (the task in the execution path) to execute the task simultaneously with other threads.

Master Thread tasks created by JVM are defined in the mian method. Custom Thread tasks will be encapsulated in the run method of the Thread class.

 

Step 1 of Method 1: 1: Inherit Thread class 2: override run method (encapsulate task) 3: instantiate subclass object of Thread class 4: call the start method to enable the thread (this method will call the run method to execute the task)

 1 class Text{ 2     public static void main(String[] args) { 3         aThread Dome=new aThread(); 4         Dome.start(); 5         System.out.println(Thread.currentThread().getName()); 6     } 7 } 8 class aThread extends Thread{ 9     public void run(){10         System.out.println(Thread.currentThread().getName());11     }12 }

CurrentThread () is a static method that returns the object of the currently running thread, and then calls the getName method to return the name of the thread;

The name is Thread-number (starting from 0), and the main function name is main.

The Thread class has a constructor that receives parameters of the String type. The imported data can be used to customize the Thread name. The following code:

1 class aThread implements Runnable{2     aThread(String a){3         super(a);4     }5     public void run(){6         System.out.println(this.getName());7     }8 }

 

If a subclass already has a parent class, but it needs to enable multithreading to execute tasks, it needs to use the Runnable interface to extend the functionality of this subclass (avoiding java's single inheritance limitations)

The Runnable interface has only one run abstract method, so the Runnable interface only exists to encapsulate tasks with run, and the Thread class also implements the Runnable interface.

  

Step 2: 1: implement the Runnable interface 2: override the run method (encapsulate the task) 3: Create Thread a to create the Runnable subclass object t

4: pass t as a parameter to a (the Thread has a constructor to receive Runnable parameters, because the tasks are encapsulated in the run method of the Runnbale subclass,

When starting a Thread, it is necessary to clarify the Thread's task. Otherwise, the Thread will call its own run method, and the task in the Runnbale subclass will never be executed)

5: start)

 1 class Text{ 2     public static void main(String[] args) { 3         aThread t=new aThread(); 4         Thread a=new Thread(t); 5         a.start(); 6         System.out.println(Thread.currentThread().getName()); 7     } 8 } 9 class aThread implements Runnable{10     11     public void run(){12         System.out.println(Thread.currentThread().getName());13     }14 }

Benefits of implementing the Runnable interface: 1. Separate tasks from the Thread subclass for separate encapsulation; encapsulate tasks into objects according to the object-oriented idea

2. Avoiding the limitations of JAVA single inheritance

 

Multithreading security issues:

Reason: 1. Multiple Threads operate on shared data

2. There are multiple codes used to operate on shared data.

When a thread executes multiple codes that share data, other threads participate in the execution, which may cause thread security problems.

Example:

1 class Text {2 public static void main (String [] args) {3 aThread t = new aThread (); 4 Thread a = new Thread (t ); 5 Thread a1 = new Thread (t); 6 Thread a2 = new Thread (t); 7 Thread a3 = new Thread (t); 8. start (); 9 a1.start (); 10 a2.start (); 11 a3.start (); 12} 13} 14 class aThread implements Runnable {15 private int mun = 100; 16 public void run () {17 while (mun> 0) {18 try {Thread. sleep (5);} catch (InterruptedException E) {} 19/* In order to be clear and freeze the thread, sleep throws an exception because the Runnable interface does not throw exception 20, so its subclass cannot be thrown, you can only try catch to catch exceptions. */21 System. out. println (Thread. currentThread (). getName () + "..... "+ mun --); 22}/* in the running result, Thread-3 ..... 42 Thread-0 ..... 4223 (if the ticket is sold, we can understand that both threads have sold the ticket No. 42, which is not allowed) */24} 25}
Solution:

Idea: When a thread operates a code block that shares data, other threads are not allowed to participate, that is, synchronization (simply put, a lock is applied to the code block that shares data, when a thread comes in, you must determine whether another thread is operating on the shared data code block)

Benefits of synchronization: security issues are solved

Disadvantages of synchronization: relatively low efficiency (because the lock needs to be determined every time)

Note: These threads must use the same lock.

Method 1: Synchronize code blocks

Method 2: Synchronous Functions

Keywords: synchronized

  

Implementation Method 1 (Synchronous Code block ):

 1 class Text{ 2     public static void main(String[] args) { 3         aThread t=new aThread(); 4         Thread a=new Thread(t); 5         Thread a1=new Thread(t); 6         Thread a2=new Thread(t); 7         Thread a3=new Thread(t); 8         a.start(); 9         a1.start();10         a2.start();11         a3.start();12     }13 }14 class aThread implements Runnable{15     private int mun=100;16     private Object obj=new Object();17     public void run(){18         while(mun>0){19             synchronized(obj){20                 if(mun<=0)return;21                 try{Thread.sleep(5);}catch(InterruptedException e){}22             System.out.println(Thread.currentThread().getName()+"....."+mun--);23             }    24         }25     }26 }

The lock of the synchronized code block can be customized. Here, the lock I defined is the object obj of the Obiect class.

 

Implementation Method 2 (synchronous function ):

 1 class Text{ 2     public static void main(String[] args) { 3         aThread t=new aThread(); 4         Thread a=new Thread(t); 5         Thread a1=new Thread(t); 6         Thread a2=new Thread(t); 7         Thread a3=new Thread(t); 8         a.start(); 9         a1.start();10         a2.start();11         a3.start();12     }13 }14 class aThread implements Runnable{15     private int mun=100;16     17     public void run(){18         while(mun>0)19         show();20     }21     public synchronized void show(){22             if(mun<=0)return;23             try{Thread.sleep(5);}catch(InterruptedException e){}24             System.out.println(Thread.currentThread().getName()+"....."+mun--);    25     }26 }

The lock of the synchronous function is fixed. this

The lock of the static synchronization function is the bytecode object (class file) to which the function belongs)

 

We recommend that you use synchronous code blocks.

Deadlock:

The nesting of synchronization has two locks, both holding the lock of the other side, causing the code to fail.

1 class Text {2 public static void main (String [] args) {3 aThread a = new aThread (true); 4 aThread a1 = new aThread (false ); 5 Thread t = new Thread (a); 6 Thread t1 = new Thread (a1); 7 t. start (); 8 t1.start (); 9} 10} 11 class aThread implements Runnable {12 private boolean flag; 13 aThread (boolean flag) {14 this. flag = flag; 15} 16 public void run () {17 if (flag) {18 synchronized (suo. suo1) {19 System. out. println ("I am the if lock 1"); 20 synchronized (suo. suo2) {21 System. out. println ("I am the if lock 2"); 22} 23} 24} else {25 synchronized (suo. suo2) {26 System. out. println ("I am elsef lock 2"); 27 synchronized (suo. suo1) {28 System. out. println ("I am else lock 1"); 29} 30} 31} 32} 33} 34 class suo {35 public static final Object suo1 = new Object (); 36 public static final Object suo2 = new Object (); 37}
Lazy applications in multithreading:

Because the lazy style does not directly instantiate the object, it enters the temporary blocking status after the Thread 0 judges the if statement, and thread 1 also enters the incoming state, which leads to the non-unique instantiation.

Sample Code that is not unique in instantiation:

 1 public class Text1 { 2  3     public static void main(String[] args) { 4         Ab a=new Ab(); 5         Ab b=new Ab(); 6         a.start(); 7         b.start(); 8         try{Thread.sleep(10);}catch(InterruptedException e){} 9         System.out.print(a.get()==b.get());10     }11 }12 class Single{13     private static Single a=null;14     private Single(){15     }16     static Single  getSingle(){17         if(a==null){18             try{Thread.sleep(10);}catch(InterruptedException e){}19             a=new Single();20         }21         return  a;22     }23 }24 class Ab extends Thread{25     private Single a;26     public void run(){27         a=Single.getSingle();28     }29     Single get(){30         return a;31     }32 }

If you try multiple times, the output result is false.

  

Solve the problem (synchronize) (the hungry Chinese code should be modified as follows ):

 1 class Single{ 2     private static Single a=null; 3     private Single(){ 4     } 5     static Single  getSingle(){ 6         if(a==null){ 7             synchronized (Single.class){ 8                 if(a==null){ 9                     a=new Single();10                }11             }12         }13         return  a;14     }15 }

NOTE: if judgment is added to the original hungry Chinese code to improve efficiency. Otherwise, the thread will always judge the lock and reduce the efficiency. This is also the reason why synchronous functions are used from time to time.

Synchronization is added to solve security problems.

Therefore, it is better to use the hungry Chinese style during development.

 

 

 

 

 

 

 

 

  

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.