Multi-threaded ticket lock lock (i)

Source: Internet
Author: User
Tags ticket
Package testlock;


Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;


Class Sellticket implements Runnable {


Define Tickets
private int tickets = 100;


Defining Lock objects
Private lock lock = new Reentrantlock ();


public void Run () {
while (true) {
try {
Locking
Lock.lock ();
if (Tickets > 0) {
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "being sold" + (tickets--) + "Ticket");
}
} finally {
Release lock
SYSTEM.OUT.PRINTLN ("release lock");
Lock.unlock ();
}
}
}


}


/*
* Although we can understand the problem of lock object of synchronous code block and synchronous method, but we do not directly see where to add the lock, where to release the lock, in order to express more clearly how to lock and release the lock, JDK5 later provided a new lock object locks.
*
* Lock:void Lock (): Gets the lock. void Unlock (): Release lock. Reentrantlock is the implementation class for lock.
*/
public class Sellticketdemo {
public static void Main (string[] args) {
Create a Resource object
Sellticket st = new Sellticket ();


Create a three window
thread T1 = new Thread (ST, "Window 1");
Thread t2 = new Thread (ST, "Window 2");
thread t3 = new Thread (St, "Window 3");


Start thread
T1.start ();
T2.start ();
T3.start ();
}
}

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.