Dark Horse programmer Series 1 multi-thread (-), dark horse programmer

Source: Internet
Author: User

Dark Horse programmer Series 1 multi-thread (-), dark horse programmer

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/1sjQRHDz)

 

Directory: i. Two ways to create threads II. Five states of threads, common methods in thread operations III. multi-thread security IV. disadvantages of using synchronization 5. multithreading in singleton design mode (interview highlights)

 

I. Two ways to create a thread

 1. Implement the Runnable interface (mainstream)

Sample Code:

 1 public class ThreadTest{ 2      3     public static void main(String[] args) throws InterruptedException{ 4       ThreadImple ti=new ThreadImple(); 5       Thread thread=new Thread(ti); 6        7       thread.start(); 8 } 9 }10  class ThreadImple implements Runnable {11 12     @Override13     public void run() {14         for(int i=0;i<60;i++)15         System.out.println("thread implements runnable..."+i);16     }17 }

2. inherit the Thread class

public class ThreadTest{        public static void main(String[] args) throws InterruptedException{      ThreadExtends ti=new ThreadExtends();           ti.start();}} class ThreadExtends extends Thread {    public void run() {        for(int i=0;i<60;i++)        System.out.println("extend thread class..."+i);    }}

 

3. Differences between the two creation methods

The Running code of the implementation method is stored in the run method of the interface subclass. The implementation method avoids the limitation of single inheritance. We recommend that you use

The Running code of the Inheritance Method is stored in the run method of the Thread subclass.

Ii. Methods Commonly Used in five State thread operations

 

 

Iii. multi-thread security

Problem: When a thread operates multiple statements to share data, one thread executes only one part of the statements, and the other thread participates in the execution, resulting in an error in data sharing.

How to find problems: 1. Identify the code that shows the multi-thread code to run. 2. Define data sharing. 3. Specify the statements in the multi-thread code to operate on shared data.

Solution: Synchronous Code block:

Synchronized (LOCK ){

Code to be synchronized;

}

Synchronous function: add the synchronized modifier before the function.

Three prerequisites must be met for synchronization.: 1. There must be two or more threads. 2. Multiple Threads must use the same lock.

Disadvantages: It is a waste of resources to judge the lock during each execution.

The lock of a common synchronous function is this, and that of a static function is the file bytecode object (. class)

Simple ticket simulation code:

1/* 2 program 1 create three threads to simulate three ticket sales windows ticket = 100 set the ticket number to 1-100. We hope the ticket number will not be repeated. 3 unfortunately, the result will show a negative ticket number., the same ticket number problem, that is, the thread insecurity problem we will talk about 4 */5 public class SaleTicketUnsafe {6 7 public static void main (String [] args) {8 9 Ticket ticket = new Ticket (); 10 11 new Thread (ticket ). start (); 12 new Thread (ticket ). start (); 13 new Thread (ticket ). start (); 14 15} 16 17} 18 class Ticket implements Runnable {19 20 private int ticket = 100; 21 public void run () {22 while (true) {23 if (ticket> 0) {24 try {25 Thread. sleep (10); // The thread error probability is not very high, so let the thread sleep () to expose the problem 26} catch (InterruptedException e) {27 // TODO Auto-generated catch block28 e. printStackTrace (); 29} 30 System. out. println (Thread. currentThread (). getName () + "sell at ticket Gate --- ticket No.:" + ticket --); 31} 32} 33 34} 35}

Improved programs using synchronous code blocks

1/* solve the problem by synchronizing code blocks */2 public class SaleTicketSafe {3 4 public static void main (String [] args) {5 Tickets ticket = new Tickets (); 6 7 new Thread (ticket ). start (); 8 new Thread (ticket ). start (); 9 new Thread (ticket ). start (); 10} 11 12} 13 class Tickets implements Runnable {14 15 private int ticket = 100; 16 Object obj = new Object (); 17 @ Override18 public void run () {19 while (true) {20 synchronized (obj) {// Synchronous Code Block 21 if (ticket> 0) {22 try {23 Thread. sleep (10); 24} catch (InterruptedException e) {25 // TODO Auto-generated catch block26 e. printStackTrace (); 27} 28 System. out. println (Thread. currentThread (). getName () + "sell at ticket Gate --- ticket No.:" + ticket --); 29} 30} 31} 32} 33 34}

 

 

4. deadlock occurs when synchronization is used (a deadlock program is required during the interview)

ProblemMultiple Threads each hold different locks that are not released, and each other needs the other's locks.

Cause: Nested synchronization in synchronization, but their locks are different

A simple deadlock program:

1 public class DieLock {2 3 public static void main (String [] args) {4 // enable two threads to Test 5 Thread t1 = new Thread (new Test (true )); 6 t1.start (); 7 Thread t2 = new Thread (new Test (false); 8 t2.start (); 9} 10} 11 class Test implements Runnable {12 boolean flag; 13 public Test (boolean f) {14 this. flag = f; 15} 16 @ Override17 public void run () {18 if (flag) {19 while (true) {20 synchronized (Lock. lockb) {21 System. out. println ("if locka"); 22 synchronized (Lock. locka) {23 System. out. println ("if lockb"); 24} 25} 26} 27} else {28 while (true) {29 synchronized (Lock. locka) {30 System. out. println ("else locka"); 31 synchronized (Lock. lockb) {32 System. out. println ("else lockb "); 33} 34} 35} 36} 37} 38 // define two separate locks 39 static class Lock {40 static Object locka = new Object (); 41 static Object lockb = new Object (); 42} 43}

 

V. multithreading In the singleton design model (interview key points)

Hungry and lazy (threads are insecure and need to be synchronized)

There are two ways to synchronize the lazy style:

1. In the following code, we will use synchronized to modify the getInstance method and use the synchronization function to solve the problem. Each time we synchronize and compare resource consumption

2. synchronous block is used in comments. dual judgment (s = null) only needs to be synchronized once to avoid excessive resource consumption. We recommend that you use

Public class Single {public static void main (String [] args) {Singlel s = Singlel. getInstance () ;}// lazy class Singlel extends Single {private Singlel () {} private static Singlel s = null; public static synchronized Singlel getInstance () {if (s = null) s = new Singlel (); // if (s = null) {// synchronized (Singlel. class) {Method 2: Double judgment to improve efficiency // if (s = null) // s = new Singlel (); //} return s ;}} // hungry class Singlee extends Single {private Singlee () {}private static Singlee s = new Singlee (); public static Singlee getInstance () {return s ;}}

Continuous correction ...........

 

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.