Common examples of Java multi-threading

Source: Internet
Author: User

I. Related knowledge:

Java multithreaded programming to the Knowledge:

(i) operation of the same quantity

(ii) operation of the same object

(c) The callback method is used

(iv) Thread synchronization, deadlock problem

(V) Thread Communication

Wait a minute

Two Example one: three ticketing Windows sell 20 tickets at the same time;

Program Analysis: 1. Number of votes to use the same static value

2. To ensure that there will not be a sell the same number of votes, Java multi-threaded synchronization Lock.

Design Ideas: 1. Create a platform class station, inherit the thread, rewrite the run method, and execute the ticket operation inside the run method! Ticket to use a sync lock: that is, there is a platform to sell this ticket, the other platform to wait for this ticket sold out!

2. Creating the Main method invocation class

(i) Create a platform class that inherits the thread

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
Package com.xykj.threadStation; public class Station extends thread {//assign a value to the thread name by means of construction method public station (String Name) {super (name);//assign A value to the thread name}//to keep the number of votes consistent, the number of votes To statically static int tick = 20; A static key is created by the passive Object OB = "aa";//value is Arbitrary//override the Run method to achieve ticket operation @overridepublic Void run () {while (tick > 0) {synchronized (ob) {//this is very important, must use a lock,//enter the person will hold the key in hand, come out after the key to let out if (tick > 0) {System.out.println (getName () + "sold the first" + tick + "ticket"); tick-- ;} Else {System.out.println ("the ticket is sold out");}} Try {sleep (1000);//break one second} catch (interruptedexception e) {e.printstacktrace ();}}} }
code slices from codesSnippet_file_0.txt

(ii) creating the Main method invocation class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21
Package com.xykj.threadStation; Use of public class MainClass {/*** java multi-threaded sync Lock * example: three ticket window sold at the same time 10 tickets * */public static void main (string[] Args) {//instantiate the platform object, and for each station The station takes the name stations of Station1=new ("windows 1"); Station Station2=new Station ("window 2"); Station Station3=new Station ("window 3"); Let each platform object start working station1.start (); station2.start (); station3.start (); } }
code slices from codesSnippet_file_0.txt

Program Run Result:

You can see the number of votes is not wrong!

Three Example Two: two person AB takes money from an account a at the counter and B takes money at the ATM machine!

Program analysis: The amount of money to be set as a static Variable. Two the same object value to be taken by a person

(I) Create a bank class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21
Package com.xykj.bank; public class Bank {///suppose an account has 1000 dollars static int money = 1000;//counter Counter method of taking money public void Counter (int Money) {//parameter is the amount taken each Time. bank.money-= money;//the Total amount decreased System.out.println ("a took away" + money + "left" + (bank.money));} ATM take money method public void ATM (int Money) {//parameter is each fetch away money bank.money-= money;//after The total reduction System.out.println ("b took away" + money + "still left" + (bank.money));} }
code slices from codesSnippet_file_0.txt

(ii) creation of a persona class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Package com.xykj.bank; public class PersonA extends Thread {//create Bank object Banks;//the Bank object is passed through the constructor, ensuring that two people enter a bank public PersonA (bank) {this.bank = bank;} Rewrite the run method, which implements using the counter to withdraw money @overridepublic void run () {while (bank.money >=) {Bank. Counter (100);//fetch 100 block try {sleep (100)///take rest 0.1 seconds} catch (interruptedexception e) {e.printstacktrace ();}}}
code slices from codesSnippet_file_0.txt

(iii) creation of a PERSONB class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Package com.xykj.bank; public class Personb extends Thread {//create Bank object Banks;//the Bank object is passed through the constructor, ensuring that two people enter a bank public personb (bank) {this.bank = bank;} Rewrite the run method, which implements using the counter to withdraw money @overridepublic void run () {while (bank.money >=) {Bank. ATM (200);//fetch 200 block try {sleep (100)///take rest 0.1 seconds} catch (interruptedexception e) {e.printstacktrace ()}} }}
code slices from codesSnippet_file_0.txt

(iv) calling class to create the Main method

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19
Package com.xykj.bank; public class MainClass {/*** two person AB takes money at the counter via an account A and B takes money at the ATM * */public static void main (string[] Args) {//strength a Bank object banks = New bank ();//instantiate Two people, passing in the same bank object PersonA PA = new PersonA (bank); Personb PB = new Personb (bank),//two people start to withdraw money Pa.start ();p B.start (); } }
code slices from codesSnippet_file_0.txt

Operation Result:

You can see that it stopped running after it was Taken.

Four Example three: the Turtle-rabbit race problem

Tortoise and Rabbit race: 20 m//just in order to see the effect, all distances shortened

Requirements:

1. The rabbit 0.5 meters per second at a speed of 2 meters per run rest 10 seconds,

2. Turtles run 0.1 meters per second, no rest

3. One of them runs to the end and the other doesn't run!

Program Design Ideas:

1. Create a animal animal class, inherit the thread, write a running abstract method, rewrite the run method, and call the running method inside the run Method.

2. Creating rabbit rabbits and tortoise turtles, inheriting animal classes

3. Two subclasses overriding the Running method

4. The 3rd requirement in this subject involves a thread callback. Need to create a callback interface in animal class to create a callback object

(i) creation of animal animal classes

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Package com.xykj.rabbit_tortoise; Public abstract class Animal extends Thread{public double length=20;//tournament length public abstract void runing ();//abstract method requires subclass implementation// In the parent class, overriding the run method, the subclass can only override the running method to @overridepublic void run () {super.run (); while (length>0) {runing ();}}// In the place where the callback data is needed (two subclass required), Declare an interface public static interface Calltoback{public void win ();}//2. Creating an Interface object public Calltoback Calltoback ; }
code slices from codesSnippet_file_0.txt

(ii) creation of the Rabbit Rabbit category

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
Package com.xykj.rabbit_tortoise; public class Rabbit extends Animal {public Rabbit () {setName ("rabbit");//thread's method, assigning name to thread}//overriding running method, writing Rabbit run operation @overri depublic void runing () {//run distance double dis = 0.5;length-= dis;//after running the distance reduction if (length <= 0) {length = 0; System.out.println ("rabbit Wins");//assign A value to the callback object so that the tortoise does not run again if (calltoback! = Null) {calltoback.win ();}} System.out.println ("rabbit ran" + dis + "meters, distance from the end of the" + (int) length + "m"); If (length% 2 = = 0) {//two m rest one time try {sleep (+),} catch (interruptedexception e) {e.printstacktrace ();}}}}
code slices from codesSnippet_file_0.txt

(iii) creation of the Tortoise Turtle class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Package com.xykj.rabbit_tortoise; public class Tortoise extends Animal {public tortoise () {setName ("turtle");//thread's method, assigning name to thread}//overriding running method, writing turtle run Operation @ov erridepublic void runing () {//run distance double dis = 0.1;length-= dis;if (length <= 0) {length = 0; System.out.println ("turtle Wins");//let The rabbit not run if (calltoback! = Null) {calltoback.win ();}} System.out.println ("tortoise ran" + dis + "m, distance to end also" + (int) length + "m"); try {sleep];} catch (interruptedexception e) {e.pri Ntstacktrace ();}}}
code slices from codesSnippet_file_0.txt

(iv) create a class that lets the animal thread stop, which implements the callback interface

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Package com.xykj.rabbit_tortoise; Import Com.xykj.rabbit_tortoise. animal.calltoback; public class Letonestop implements Calltoback {//animal object Animal an;//get An animal object that can be passed into the instance of the Hare or tortoise public letonestop (Animal A) {this . an = an;} Let the Animal's thread stop @overridepublic void win () {//thread stop An.stop ();}}
code slices from codesSnippet_file_0.txt

(V) Create a Main method invocation class,

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22
Package com.xykj.rabbit_tortoise; public class MainClass {/*** Turtle rabbit race: 20 m * */public static void main (string[] Args) {//instantiate turtle and rabbit Tortoise tortoise = new Tortois E (); Rabbit Rabbit = new Rabbit ();//the use of callback methods, who first call the Calltoback method, the other will not run letonestop LETONESTOP1 = new Letonestop (tortoise); Rabbit.calltoback = Letonestop1;//let The Rabbit's callback method inside the Turtle object value, you can put the turtle stopletonestop letOneStop2 = new Letonestop (rabbit); Tortoise.calltoback = Letonestop2;//let The Turtle's callback method inside the Rabbit object value, You can start the rabbit stop//run tortoise.start (); rabbit.start (); } }
code slices from codesSnippet_file_0.txt

Operation Result:

Can see the result the rabbit Won.

In general, the rabbit wins the final output,

however, the thread will appear because it is always executing:

"the Rabbit ran 0.5 meters, from the end of the 0 meters" before the output is finished,

and "the Rabbit has won" has been output finished.

Five Example Four:

In a kfc, the waiter is responsible for the production of food, consumers are responsible for consuming food;

When the production to a certain amount can rest, until the consumption of food, and then immediately production, has been circulating

What the program Involves:

1. This design to the Java mode idea: producer consumer model

2. To ensure that the operation of the unity of the object, that is, consumers and service providers are related to the same kfc, KFC can only new once

3.this.notifyall (); and This.wait (); one is the meaning of all awakening, one is to let oneself wait;

For example, when the producer is finished, all wake up (both consumers and producers), and then all of them (producers) wait

At this point, consumers begin to consume, until the ingredients are not enough, to awaken all (including consumers and producers) and then let all themselves (consumers) wait

The loop that has been performing the above operation

4. Both producers and consumers inherit thread to enable multi-threaded startup

Procedure of program Design:

1. Create a food meal with a way to store/get the name of the food

2. Create a KFC class that has the means to produce food and consume food

3. Create a client class customer, inherit the thread, override the run method, and consume food operations inside the Run method

4. Create a waiter class waiter, inherit the thread, rewrite the run method, and make food production operations in the run Method.

5. Create a calling class for the Main method

(i) Creation of food products

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
Package com.xykj.producer_consumer; public class food {string name= "";//the name of the feed passed through the construction method public Foods (string Name) {this.name=name;} get, Set method public String getName () {return name;} public void SetName (String Name) {this.name = name;}}
code slices from codesSnippet_file_0.txt

(ii) creation of a KFC class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
Package Com.xykj.producer_consumer;import Java.util.arraylist;import Java.util.list; public class KFC { // Type of food string[] names = {"fries", "burning plate", "chicken wings", "cola"}; //the maximum value of production, can rest after arrival static final int Max = 20; //set of food storage List<fo Od> foods = new arraylist<food> ()  //method of producing food public void prod (int. Index) {synchronized (this) {//if Food quantity is greater than 20 While (foods.size () > Max) {System.out.println ("food is enough"), this.notifyall ();//this Wakeup is for producers and consumers, there is alltry {String name= Thread.CurrentThread (). getName (); this.wait ();//this Awakening is directed at the producer, without allSystem.out.println ("producer:" +name);} Catch (interruptedexception e) {e.printstacktrace ();}}  //start to produce food///a little attention to System.out.println ("start food production"); for (int i = 0; i < index; i++) {foodstuffs food = new Foods (names[(int ) (math.random () * 4)]); foods.add (food); System.out.println ("produced" + food.getname () + foods.size ());}}}  //method of consuming food public void Consu (int Index) {synchronized (this) {while (foods.size () < Index) {System.out.println ("food This.notifyall ();//this wake-up is a needleFor producers and consumers, there are alltry {String name=thread.currentthread (). getName (); this.wait ();//this wake-up is for consumers, no allSystem.out.println ( "consumer:" +name);} Catch (interruptedexception e) {e.printstacktrace ();}} Enough consumption System.out.println ("start consumption"); for (int i = 0; i < index; i++) {food food = foods.remove (foods.size ()-1); System.out.println ("consumed a" + food.getname () + foods.size ());}}}}
code slices from codesSnippet_file_0.txt

(iii) creation of a customer class customers

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18
Package com.xykj.producer_consumer; public class Customers extends THREAD{KFC KFC;//KFC to be passed in, to ensure that each waiter and user within the same KFC object public Customers (KFC Kfc) {this.kfc=kfc;} @Overridepublic void Run () {int size= (int) (math.random ());//the quantity of food to be consumed at a time (true) {kfc.consu (size);// Pass in the parameter in the consumption method}}}
code slices from codesSnippet_file_0.txt

(iv) creation of a waiter class waiter

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17
Package com.xykj.producer_consumer; public class Waiter extends THREAD{KFC KFC;//KFC to be passed in, to ensure that each waiter and user within the same KFC object public waiter (KFC Kfc) {this.kfc=kfc;} @Overridepublic void Run () {int size= (int) (math.random ()) +5;//quantity per production while (true) {kfc.prod (size);//number of incoming per production}}}
code slices from codesSnippet_file_0.txt

(v) calling class to create the Main method

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
Package com.xykj.producer_consumer; public class MainClass {/*** producer Consumer mode * * */public static void main (string[] Args) {//instantiate only one KFC object, guaranteeing each waiter and user within the same KFC object KFC KFC = new KFC (); Instantiate 4 Customer objects Customers C1 = new Customers (kfc); Customers C2 = new Customers (kfc); Customers C3 = New Customers (kfc); Customers C4 = new Customers (kfc); Instantiation of 3 Waiter objects Waiter Waiter1 = new Waiter (kfc); Waiter Waiter2 = new Waiter (kfc); Waiter Waiter3 = new Waiter (kfc); Let all the threads of the object begin to work Waiter1.start (); waiter2.start (); waiter3.start (); c1.start (); c2.start (); c3.start (); c4.start ();} }
code slices from codesSnippet_file_0.txt

Six Example Five: design four thread objects to operate on the same data,

Two threads perform a subtraction operation, and two threads perform a plus operation.

Program Analysis: 1. Create a threadaddsub class to inherit the thread, overriding the Run method

2. Add and subtract in the run method, sleep for 1 seconds after each operation

3. Creating the Main method invocation class

(i) Create a Threadaddsub class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
Package com.xykj.add; public class Threadaddsub extends Thread {//determines the operation to be performed by Boolean operate = true;//the number of static int sum = 0;//the operation is passed through the construction method pub Lic threadaddsub (boolean Operate) {super (); this.operate = operate;} @Overridepublic void run () {super.run (); while (true) {if (operate) {sum+=5; System.out.println ("plus, sum=" +sum); else {sum-=4; System.out.println ("minus, sum=" +sum); Try {sleep (500);//sleep 0.5 seconds} catch (interruptedexception e) {e.printstacktrace ()}} }}
code slices from codesSnippet_file_0.txt

(ii) creating the Main method invocation class

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Emptypackage com.xykj.add; public class MainClass {/*** (thread sync) * */public static void main (string[] Args) {//create an array that holds Threadaddsub objects threadaddsub[] TS Ub=new threadaddsub[4];for (int i = 0; i < tsub.length; i++) {//assigns an instantiated Threadaddsub object to the array//13th is true, 24 is falsetsub[i]= New Threadaddsub (i%2==0?true:false); Let the thread start working Tsub[i].start ();} } }
code slices from codesSnippet_file_0.txt

Thread Sample Summary:

Block locks are an important means of preventing data from occurring incorrectly.

The unity of the object is very important, it is to think of the Object's incoming problem,

The object to be manipulated can only be new once, and the other operations are performed on the incoming object,

To ensure data consistency, completeness and correctness.

Practice Topics:

1. (multi-threaded) code implementation of the railway station 4 ticket window at the same time the scene of the ticket, output example:
Window 1 Selling tickets
Window 2 selling Tickets
Window 1 Selling tickets
...
2. (thread Synchronization) Code Realization railway station 4 windows simultaneously sell 100 ticket code logic, the same window cannot sell the same
Ticket.
3. (thread Communication) Xiao Ming plans to go to the ATM to withdraw money, found that there is no money on the card, when he told his mother to save money, mom
Save the money, tell Xiao Ming save good can withdraw money. (PS: Xiao Ming several times to take the money, each fetch 100, when found that the money is not enough
100, waiting for mom to save money, Xiao Ming his mother every time to save 2000, when found that less than 100 of money to save, save money, and
Inform Xiao Ming to fetch money, when more than 100 waiting for Xiao Ming money is not enough to Save.
4. (thread Synchronization) Design four thread objects to operate on the same data, two threads to perform subtraction, two threads to execute
Added Operation.
5. (thread Communication) making two thread objects, requiring the first thread to run 2 times with a synchronous block, and then
Block up, Wake up the second thread, run the second thread 2 more times, then block yourself and wake up the first Line.
Ride...... Two threads are executed alternately.
6. (thread Synchronization) Design 4 threads, of which two threads add 1 to J each time, and two threads per 1 for J.
7. (thread Communication) The Sub-thread loops 10 times, then the main thread loops 100, then goes back to the child thread loop 10 times, and then
Then back to the main thread and loop 100, so loop 50 times.

Common examples of Java multi-threading

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.