Java Multithreading Summary case

Source: Internet
Author: User
Tags semaphore

After learning the things, to learn to summarize, learn to record notes, so that there will be a greater harvest


First we understand the basic concepts of threading and processes

first, the concept (program process thread)

1. Program: Instruction set static concept

2. Process: Dynamic concept of operating system scheduler

3: Threads: Multiple execution paths within the process true multithreading refers to multiple CPUs

Second, create

1.1 Inheriting thread +run ()

Start: Create class object + object. Start ()

Package com.org.pc;/** * Mock Turtle rabbit Race * @author lyy * Create multithreaded Inheritance thread rewrite run (thread body) * Use thread to create subclass object, Call object. Start () */public class Rabbit Extends thread{@Overridepublic void Run () {for (int i = 0; I <100; i++) {System.out.println ("rabbit ran" + i + "step");}} public static void Main (string[] args) {Thread T1 = new Rabbit (); Thread t2 = new Tortoise (); T1.start (); T2.start ();}} Class Tortoise extends thread{@Overridepublic void Run () {for (int i = 0; I <100; i++) {System.out.println ("turtle ran" + i + "Step");}}}

1.2Implement Runable+run ()

Start: Use static proxy

1. Create a real role

2. Create a proxy role thread+ reference

3. Agent role. Start ()

/** * Create thread with runable * 1, class implementation runable interface + rewrite run () Real role class * 2, start multithreading using static proxy * 1) Create real role * 2) Create proxy role + real role reference * 3) call. Start () * @auth or Lyy * */public class Programer implements runnable{@Overridepublic void Run () {for (int i = 0; i <; i++) {Syste M.out.println ("Knock on the code .....") ");}} public static void Main (string[] args) {//1) creates a real role programer pro = new Programer ();//2) Create proxy role + real role reference thread proxy = new THR EAD (PRO);//3) call. Start () Proxy.start (); for (int i = 0; i <; i++) {System.out.println ("chat qq ... ");}}}

1.3Implement callable (Learn)

Multithreading through the callable interface

Pros: You can get the return value


Package Com.org.pc;import Java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorcompletionservice;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.future;/** * Create thread with callable * @author Lyy * */public class  Call {public static void main (string[] args) throws Interruptedexception, Executionexception {//create thread Executorservice ser = Executors.newfixedthreadpool (2); Race tor = new Race ("Millennium King VIII", 1000); Race rabbit = new Race ("Bunny", 500);//Get value future<integer> result1 = Ser.submit (Tor); future<integer> result2 = Ser.submit (rabbit); Thread.Sleep (2000);//Hibernate 2 seconds Tor.setflag (FALSE);//Stop Loop Rabbit.setflag (false) in thread body,//stop loop int num1 = Result1.get () in thread body; int num2 = Result2.get (); System.out.println ("Big turtle ran----->" +num1+ "Step"); System.out.println ("Bunny ran----->" +num2+ ");//Stop service Ser.shutdown ();}} Class Race implements Callable<integer>{private String name;//name Private long time;//delay time PRIvate Boolean flag = true;private int step = 0;//Steps Public Race () {}public Race (String name) {super (); this.name = name;} Public Race (String name, int time) {super (); this.name = Name;this.time = time;} @Overridepublic Integer Call () throws Exception {while (flag) {Thread.Sleep (time);//delay step++;} return step;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public long GetTime () {return time;} public void SetTime (long time) {this.time = time;} public Boolean Isflag () {return flag;} public void Setflag (Boolean flag) {This.flag = flag;} public int Getstep () {return step;} public void SetStep (int step) {this.step = step;}}



Three: Thread Run



New-----ready-to-run-blocking


Four: Termination of thread (emphasis)

1, natural termination: Thread body Normal execution completed

2. External interference

1) define the identity used by the thread body in the thread class

2) The thread provides the use of the identity

3) External provision of methods to change the logo

4) Externally invoke the method according to the condition


Package Com.org.status;public class StopDemo1 {public static void main (string[] args) {Study stu = new Study (); new Thread (Stu). Start ();  Externally changes the identifier for (int i = 0; i < i++) {if (i==50) {//External interference stu.stop ();} System.out.println ("main ..." +i);}} Class Study implements RUNNABLE{//1) thread class defines the identity used by the thread body private boolean flag =true; @Overridepublic void Run () {//2) line Chengti use the identity wh Ile (flag) {System.out.println ("Study thread ...");}} 3), external provision method change the identity public void Stop () {This.flag = false;}}


Five: Blocking

IsAlive () Determines whether the thread is still alive, and that the thread is not yet terminated

GetPriority () Gets the priority value of the thread

SetPriority () Sets the priority value of the thread

SetName () give the thread a name

GetName () Gets the name of the thread

CurrentThread () Gets the currently running thread object, which is to get itself

Blocking: Join yield sleep(Focus)


1. Join: Merge Thread


Package com.org.status;/** * Join: Merge thread * @author Lyy * */public class JoinDemo01 extends Thread {public static void main (S Tring[] args) throws interruptedexception {JoinDemo01 Join  = new JoinDemo01 (); Thread t = new thread (join);//New T.start ();//Ready//CPU dispatch run for (int i = 0; i <; i++) {if (= = i) {t.join ();//main Block}sys Tem.out.println ("main ..." +i);}} @Overridepublic void Run () {for (int i = 0; i < i++) {System.out.println ("Join ..." +i);}}



2. Yield: Suspend your own thread

Package Com.org.status;import Javax.sound.midi.synthesizer;public class YieldDemo01 extends thread{public static void Main (string[] args) {YieldDemo01 yield = new YieldDemo01 (); Thread t = new thread (yield),//New T.start ();//Ready//CPU dispatch run for (int i = 0; i <; i++) {if (i%20 = = 0) {//pause this thread mainthread. Yield ();} System.out.println ("main ..." +i);}} @Overridepublic void Run () {for (int i = 0; i < i++) {System.out.println ("yield ..." +i)}}



3, Sleep (): Hibernate, do not release the lock

1), Time-related (countdown)

Package Com.org.status;import Java.text.simpledateformat;import java.util.date;/** * Countdown * 1, 10 count, one second to print a * 2, Countdown * @au Thor Lyy * */public class SleepDemo01 {public static void main (string[] args) throws Interruptedexception {Date EndTime = New Date (System.currenttimemillis () + 10*1000), long end = Endtime.gettime (), while (true) {//Output System.out.println (new SimpleDateFormat ("Mm:ss"). Format (endTime));//build next second time EndTime = new Date (Endtime.gettime ()-1000);// Wait a second time thread.sleep (1000),//if within 10 seconds to continue otherwise exit if (end-10000 > Endtime.gettime ()) {System.out.println ("ending"); public static void Test1 () throws Interruptedexception{int num = 10;while (true) {System.out.println (num--); Thread.Sleep (1000);//pause if (num <= 0) {break;}}}}


2), Analog network delay

Package com.org.status;/** * Sleep analog Network delay thread insecure * @author Lyy * */public class SLeepDemo02 {public static void main (Strin G[] (args) {//real role Web12306 web = new Web12306 ();//proxy role Thread t1 = new Thread (web, "engineer"); Thread t2 = new Thread (web, "Ox has"); thread t3 = new Thread (web, "passer-by");//Start thread T1.start (); T2.start (); T3.start ();}} Class Web12306 implements runnable{private int num = @Overridepublic void run () {while (true) {if (num <= 0) {break;//jumps out Loop}try {thread.sleep ($);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed" +num--);}}}


Synchronization: Multiple threads concurrently accessing the same resource to ensure resource security ==> thread safety

Synchronized---Sync

One, synchronous block

Synchronized (reference type |this| Class) {

 }


Package Com.org.syn;public class SynDemo01 {public static void main (string[] args) {//real role Web123 web = new Web123 ();//proxy role thread T1 = new Thread (web, "engineer"); Thread t2 = new Thread (web, "Ox has"); thread t3 = new Thread (web, "passer-by");//Start thread T1.start (); T2.start (); T3.start ();}} Class Web123 implements runnable{private int num = 10;private Boolean flag = true; @Overridepublic void Run () {while (flag) { Test3 ();}} Thread insecure lock resource incorrect public void Test6 () {//a b CIF (num <= 0) {flag =false;//jump out of loop return;} Synchronized (this) {try {thread.sleep (500);//Analog delay} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed" +num--);}} Thread insecure lock resource incorrect public void Test5 () {//a b csynchronized ((Integer) num) {if (num <= 0) {flag =false;//jump out of loop return;} try {thread.sleep (500);//Analog delay} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed" +num--);}} The lock range is incorrect public void test4 () {//a b csynchronized (this) {if (num <= 0) {flag =FAlse;//jumps out of the loop return;} try {thread.sleep (500);//Analog delay} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed" +num--);}} Thread safe, lock the correct public void Test3 () {//a b csynchronized (this) {if (num <= 0) {flag =false;//jump out of loop return;} try {thread.sleep (500);//Analog delay} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed" +num--);}} Public synchronized void Test2 () {if (num <= 0) {flag =false;//jumps out of loop return;} try {thread.sleep (500);//Analog delay} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed" +num--); Thread unsafe public void test1 () {if (num <= 0) {flag =false;//jumps out of loop return;} try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "grabbed" +num--);}}


Second, the synchronization method

Synchronized

Thread-safe efficiency is slow and resources are guaranteed to be correct

Thread insecurity is fast and efficient

Third, deadlock: Too much synchronization is prone to deadlock



Package com.org.syn;/** * Excessive method may cause deadlock * @author Lyy * */public class SncDemo3 {public static void main (string[] args) {OBJ ECT g = new Object (); object m = new Object (); Test T1 = new test (G,M); Test t2 = new test (G,M); Thread proxy1 = new Thread (t1); Thread Proxy2 = new Thread (t2);p Roxy1.start ();p Roxy2.start ();}} Class Test implements Runnable{object Goods;object money;public Test (object goods, object money) {this.goods = Goods;this. Money = money;} @Overridepublic void Run () {while (true) {Test ()}} public void Test () {synchronized (goods) {try {Thread.Sleep ($)} catch (Interruptedexception e) {e.printstacktrace ()}} Synchronized (Money) {//system.out.println ("hand Delivery");}}} Class Test2 implements Runnable{object Goods;object money;public test2 (object goods, object money) {this.goods = Goods;thi S.money = money;} @Overridepublic void Run () {while (true) {Test ()}} public void Test () {synchronized (money) {try {Thread.Sleep ($)} catch (Interruptedexception e) {e.printstacktrace ();}} Synchronized (goods) {SYstem.out.println ("Hand Delivery");}}} 


Solution: Producer Consumer Model

First production, in the consumption

package com.org.pro;/** * A scene, a common resource * producer and Consumer mode Semaphore method * Wait () Waiting for release lock sleep does not release lock * Notify ()/notifyall () wake up * with synchronized * @a Uthor Lyy * */public class Movie {private String pic;//semaphore//flag-T producer production consumer consumer production finished notify consumption//flag--F consumer consumer producers, etc. Wake-up production after consumption is complete private Boolean flag = True;public synchronized void Play (String pic) {if (!flag) {//producer waits for try {this.wait ();} CATC H (interruptedexception e) {e.printstacktrace ();}} Start production try {Thread.Sleep),} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("produced:" +pic);//production completed this.pic = pic;//notice consumption this.notify ();//producer Stop This.flag=false;} public synchronized Void Watch () {if (flag) {///consumer waits for try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ( );} try {//Start consuming thread.sleep ($);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Consumed:" +pic);//consumer finished//Notification production this.notify ();//consumption stop This.flag = True;}} 


Package com.org.pro;/** * Producer * @author Lyy */public class Player implements Runnable{private movie M;public Player (movie m) {super (); this.m = m;} @Overridepublic void Run () {for (int i = 0; i < i++) {if (0 = = i%2) {M.play ("left Tsing Lung");} Else{m.play ("Right white Tiger");}}}

Package com.org.pro;/** * Consumer * @author Lyy * */public class Watcher implements Runnable{private Movie M;public watcher (Mo Vie m) {super (); this.m = m;} @Overridepublic void Run () {for (int i = 0; i <; i++) {M.watch ();}}}

Package Com.org.pro;public class App {public static void main (string[] args) {//common resource movie m = new Movie ();//multithreaded player P = New Player (m); Watcher W = new Watcher (m); new Thread (P). Start (); new Thread (W). Start ();}}


New-----------------stop

Thread is a useful but also a bit complex technology, Bo Master will be just a little fur, hope to have the opportunity to learn more with you! There is something wrong, please forgive us!

To be more proficient in threading requires a lot more in-depth understanding!


Java Multithreading Summary case

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.