Simple multi-threaded ticket simulation program (lock to solve multi-threaded existence of large security risks)

Source: Internet
Author: User

——————————————————————

jdk1.5 Lock instead of synchronized,condition package

Object in Sleep,wait,notify, Notifyall

——————————————————————

/*
Demand:
Write a simple multithreaded simulation to buy tickets for the program
Four ticket windows, a total of 100 tickets

*/
Import java.util.concurrent.locks.*;
Class Tick implements runnable{
private static int tick=100;
Private String window;
To create a lock object
Private Lock lock=new Reentrantlock ();
To create a condition object by locking an object
Private Condition con=lock.newcondition ();
public void Windowname (String window) {
This.window=window;
}
public void Show (Object obj) {
System.out.println (obj);
}
public void Run () {
Locking
Lock.lock ();
try{
while (tick>0) {
Equivalent to a previous lock. Sleep (1);
Con.awaitnanos (1);
if (tick>0)
Show (window+ ":" +tick--+ "ticket");
}
}catch (Exception e) {}
finally{
Show (window+ ": The ticket has been sold out");
Unlock
Lock.unlock ();
}
}
}

public class ticketdemo{
public static void Main (String args[]) {

Tick tick0=new tick ();
Tick tick1=new tick ();
Tick tick2=new tick ();
Tick tick3=new tick ();
Thread t0=new thread (TICK0);
Thread t1=new thread (TICK1);
Thread t2=new thread (TICK2);
Thread t3=new thread (TICK3);
Tick0.windowname ("Window 1");
Tick1.windowname ("Window 2");
Tick2.windowname ("Window 3");
Tick3.windowname ("Window 4");
T0.start ();
T1.start ();
T2.start ();
T3.start ();
}

}

Simple multi-threaded ticket simulation program (lock to solve multi-threaded existence of large security risks)

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.