Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of JAVA multithread programming example

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge points of JAVA multithreaded programming example analysis, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.

1. 20 tickets are sold at three ticket windows at the same time.

Program analysis: (1) the number of votes to use the same static value (2) to ensure that the same number of votes will not be sold, to java multithreaded synchronization lock. Design idea: (1) create a platform class Station, inherit Thread, rewrite the run method, and perform ticketing operations in the run method! Tickets should be sold with a synchronization lock: when one platform sells the ticket, the other platforms have to wait for the ticket to be sold out! (2) create the main method call class

(1) create a platform class that inherits Thread

Package com.xykj.threadStation

Public class Station extends Thread {

/ / assign a value to the thread name by constructor

Public Station (String name) {

Super (name); / / assign a value to the thread name

}

/ / in order to keep the number of votes consistent, the number of votes should be static

Static int tick = 20

/ / create a static key

Static Object ob = "aa"; / / the value is arbitrary

/ / override the run method to realize the ticket purchase operation

@ Override

Public void run () {

While (tick > 0) {

Synchronized (ob) {/ / this is important, you must use a lock

/ / the person who goes in will take the key in his hand and give it out only when he comes out.

If (tick > 0) {

System.out.println (getName () + "sold No." + tick + "ticket")

Tick--

} else {

System.out.println ("tickets are sold out")

}

}

Try {

Sleep (1000) / / take a break for a second

} catch (InterruptedException e) {

E.printStackTrace ()

}

}

}

}

(2) create the main method call class

Package com.xykj.threadStation

Public class MainClass {

/ * *

* use of java multithreaded synchronization locks

* example: 10 tickets are sold at three ticket windows at the same time

* * /

Public static void main (String [] args) {

/ / instantiate the platform object and give each platform a name

Station station1=new Station ("window 1")

Station station2=new Station ("window 2")

Station station3=new Station ("window 3")

/ / Let each platform object start to work separately

Station1.start ()

Station2.start ()

Station3.start ()

}

}

The result of running the program:

Window 1 sold the 20th ticket.

Window 2 sold the 19th ticket.

Window 3 sold the 18th ticket.

Window 3 sold the 17th ticket.

Window 1 sold the 16th ticket.

Window 2 sold the 15th ticket.

Window 3 sold the 14th ticket.

Window 1 sold the 13th ticket.

Window 2 sold the 12th ticket.

Window 2 sold the 11th ticket.

Window 1 sold the 10th ticket.

Window 3 sold the ninth ticket.

Window 3 sold the eighth ticket.

Window 1 sold the seventh ticket.

Window 2 sold the sixth ticket.

Window 3 sold the fifth ticket.

Window 1 sold the fourth ticket.

Window 2 sold the third ticket.

Window 3 sold the second ticket.

Window 1 sold the first ticket.

The tickets are sold out.

You can see that there is nothing wrong with the number of votes!

two。 Two people AB withdraw money at the counter through an account An and B at the ATM!

Program analysis:

The amount of money should be set to a static variable, two people want to take the same object value. (1) create a Bank class

Package com.thread.demo.demo2

Import java.util.Objects

Public class Bank {

/ / suppose an account has 1000 yuan

Static double money = 1000

/ / method of withdrawing money from counter Counter

Private void Counter (double money) {

Bank.money-= money

System.out.println ("withdraw money at the counter" + money + "yuan, leaving" + Bank.money + "yuan!")

}

/ / ATM's method of withdrawing money

Private void ATM (double money) {

Bank.money-= money

System.out.println ("ATM withdraws money" + money + "yuan, leaving" + Bank.money + "yuan!")

}

/ / provide an external withdrawal way to prevent the concurrent balance from displaying errors when the direct withdrawal method withdraws money at the same time.

Public synchronized void outMoney (double money, String mode) throws Exception {

If (money > Bank.money) {

/ / check whether the balance is sufficient

Throw new Exception ("withdrawal amount" + money+ ", balance only" + Bank.money+ ", withdrawal failed")

}

If (Objects.equals (mode, "ATM")) {

ATM (money)

} else {

Counter (money)

}

}

}

(2) create a PersonA class

Package com.thread.demo.demo2

Public class PersonA extends Thread {

Bank bank

String mode

Public PersonA (Bank bank, String mode) {

This.mode = mode

This.bank = bank

}

While (bank.money > = 100) {

Try {

Bank.outMoney (100,100, mode)

} catch (Exception E1) {

/ / TODO Auto-generated catch block

E1.printStackTrace ()

}

Try {

Sleep (100)

} catch (InterruptedException e) {

/ / TODO Auto-generated catch block

E.printStackTrace ()

}

}

}

}

(3) create a PersonB class

Package com.thread.demo.demo2

Public class PersonB extends Thread {

Bank bank

String mode

Public PersonB (Bank bank, String mode) {

This.bank = bank

This.mode = mode

}

Public void run () {

While (bank.money > = 200) {

Try {

Bank.outMoney (200, mode)

} catch (Exception E1) {

/ / TODO Auto-generated catch block

E1.printStackTrace ()

}

Try {

Sleep (100)

} catch (InterruptedException e) {

/ / TODO Auto-generated catch block

E.printStackTrace ()

}

}

}

}

(4) create the calling class of the main method

Package com.thread.demo.demo2

/ * *

* two people AB withdrew money through an account An at the counter and B at the ATM

* * /

Public class MainClass {

Public static void main (String [] args) {

Bank bank = new Bank ()

/ / instantiate two people and pass in the object of the same bank

PersonA a = new PersonA (bank, "Counter")

PersonB b = new PersonB (bank, "ATM")

A.start ()

B.start ()

}

}

You can see that it stops running after picking it up.

3. The problem of race between tortoise and hare

Tortoise and Hare Race: 2000 meters

Request:

(1) the rabbit has a speed of 5 meters every 0.1 second and a break of 1 second every 20 meters.

(2) the tortoise runs 2 meters every 0.1 second without rest.

(3) one of them ran to the finish line and the other stopped running!

Programming ideas:

(1) create an Animal animal class, inherit Thread, write an running abstract method, rewrite the run method, and call the running method in the run method.

(2) create Rabbit hare and Tortoise tortoise, inherit animals

(3) two subclasses override the running method

(4) the third requirement of this question involves a thread callback. You need to create a callback API and a callback object in the animal class.

(1) create Animal animals

Package com.thread.demo.demo3

Public abstract class Animal extends Thread {

Public int length = 2000 position / length of competition

Public abstract void runing ()

@ Override

Public void run () {

Super.run ()

While (length > 0) {

Runing ()

}

}

/ / declare an interface where callback data is needed (required by two subclasses)

Public static interface Calltoback {

Public void win ()

}

/ / 2. Create an interface object

Public Calltoback calltoback

}

(2) create Rabbit rabbits

Package com.thread.demo.demo3

Public class Rabbit extends Animal {

Public Rabbit () {

SetName (Rabbit)

}

@ Override

Public void runing () {

/ / Rabbit speed

Int dis = 5

Length-= dis

System.out.println ("Rabbit ran away" + dis + "meters, there is still" + length + "meters" from the finish line)

If (length

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report