Synchronization (Troubleshooting multithreading security issues)

Source: Internet
Author: User
Tags thread class ticket

1. Two ways to create a thread.

(1) Inherit thread (this class defines a function that stores the code that the thread will run, which is the run method, that is , the Run method in the thread class, which stores the code that the thread wants to run.) )


  
(2) Implement runnable (only an abstract method is defined in runable, public void Run ();)

Step: 1, define the class implementation runable interface 2, overwriting the Run method in the Runable interface.Store the code that the thread will run in the Run method.     3, the thread object is established through the thread class. 4, pass the subclass object of the Runable interface as the actual parameter to the constructor of the thread class.why pass the subclass object of the Runable interface to the constructor of the thread class. Because, the object that the custom run method belongs to is the subclass object of the Runable interface. So let the thread specify the run method of the specified object.    You must specify the object to which the Run method belongs.      5, call the Start method of the thread class to open the thread and invoke the Run method of the subclass of the Runable interface. The public thread (Runnable target) and public thread (Runnable target,string name) are provided in the Thread class for two construction methods


    The difference between the two ways?

Inherit thread: The threading code is stored in the thread subclass of the Run method to implement runable: The thread code has the Run method of the subclass of the interface.the thread class is also a subclass of Runnable. That is, thesubclasses of thread and runnable both implement the Runnable interface, and then place the subclass instance of runnable in the thread class. The difference between the thread class and the Runnable interface is that if a class inherits the thread class, it is not suitable for multiple threads to share resources, and implements the Runnable interface, which makes it easy to share the resources. 2. There is a security issue with multi-threaded operation. Cause of the problem: When multiple statements are working on the same thread to share data,one thread executes a portion of multiple statements, not finished, and another is involved in executing。 The error that caused the shared data. WORKAROUND: A statement that shares data on multiple operations can only be performed by one thread, and no other threads can participate in the execution. Java for multi-threaded security issues, provides a professional solution, is to synchronize the code block.Synchronous code block format:SynchronizedObject 1{The code that needs to be synchronized}The object in this 1 is like a lock, a thread holding a lock, and the code that needs to be synchronized can be executed in the synchronization .。a thread that does not have a lock does not get into it even if it obtains the CPU's execution, because it does not acquire a lock. Prerequisites for synchronization:(1)there must be two or more than two threads. (2)must have multiple threads and use the same lock。you must ensure that only one thread in the synchronization is running. Benefits and drawbacks of synchronization: Benefits: Resolves thread security issues. Cons: Multiple threads outside of synchronization areneed to determine the lock, (These are invalid judgments) consume more resources.
Package Org.lxh.demo9.threaddemo;class Ticket implements runnable{    private  int tick=5;    public void Run () {        synchronized (true) {  //this is a lock.                if (tick>0) {                try{                    thread.sleep ($);                }                catch (Exception e) {                }                System.out.println (Thread.CurrentThread (). GetName () + "sale ..." +tick--);}            }} public class Ticketdemo {public    static void Main (string[] args) {        Ticket t=new Ticket ();        Thread t1=new thread (t);//created a thread        t2=new thread (t);//created a thread        t3=new thread (t);//created a thread        T1.start ();        T2.start ();        T3.start ();    }}

3. Deadlock

One of the common scenarios: synchronized nesting

Class Test implements Runnable{private Boolean flag; Test (Boolean flag) {This.flag = flag;} public void Run () {if (flag) {while (true) synchronized (Mylock.locka) {System.out.println (Thread.CurrentThread ()). GetName () + ".. If   locka ...); synchronized (mylock.lockb) {System.out.println (Thread.CurrentThread (). GetName () + "... If lockb ....}}}   Else{while (True) synchronized (mylock.lockb) {System.out.println (Thread.CurrentThread (). GetName () + "... else  lockb); synchronized (Mylock.locka) {System.out.println (Thread.CurrentThread (). GetName () + "... else   locka ... ");}}}} Class Mylock{public static Final Object Locka = new Object ();p ublic static Final Object lockb = new Object ();} Class Deadlocktest {public static void main (string[] args) {Test a = new Test (true); Test B = new test (false); thread T1 = new Thread (a); Thread t2 = new Thread (b); T1.start (); T2.start ();}}

Running result: Thread1. Else lockb ...

Thread0. If Locka ...

You can see that thread 1 got the LOCKB lock, and thread 0 got the Locka lock, and then there was a deadlock, because thread 1 got lockb lock, still want to run down, need to get locka lock, and Locka lock thread 0 there; threads 0 Get Locka Lock, want to go down, Need to get locka lock, but lockb lock thread 1 there. This creates a deadlock.

Synchronization (Troubleshooting multithreading security issues)

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.