Java Multi-threaded simulation parking problem

Source: Internet
Author: User

/** * */package synchronized;/** * @author Libin * */public class Cartest {public static void main (string[] args) {Carset CAR1 = new Carset (); Thread T1 = new Inthread ("1", car1); Thread t2 = new Inthread ("2", car1); Thread t3 = new Inthread ("3", car1); Thread T4 = new Outthread ("4", car1); Thread T5 = new Outthread ("5", car1); T1.start (); T2.start (); T3.start (); T4.start (); T5.start ();}} Class Inthread extends thread//inbound threads {String name; Carset car;public Inthread () {}public inthread (String name,carset car) {super (name); this.car = car;} public void Run () {car. CarIn ();}} Class Outthread extends thread{string name; Carset carset;public Outthread () {}public outthread (String name,carset carset) {super (name); this.carset = Carset;} public void Run () {carset.carout ();}} Class carset{//string Carname;private boolean[] place = new Boolean[3];p ublic carset () {}//public Carset (String Carsetname)//{//this.carname = carsetname;//}public synchronized void CarIn () {try{if (place[0]&&place[1] &&place[2]) {System.out. println ("The parking space is full, please wait." "); Wait ();} for (int i = 0; i < 3; i++) {if (place[i] = = false)//spaces empty, can be put into storage {System.out.println (Thread.CurrentThread (). GetName () + "can enter" +i+ "library");p lace[i] = True;notifyall (); catch (Interruptedexception e) {e.printstacktrace ();}} Public synchronized void Carout () {try{if (!) ( place[0]| | place[1]| | Place[2]) {wait ();} for (int i = 0; i < 3; i++) {if (place[i] = = true)//vehicle in the library, can be out of the library {System.out.println (Thread.CurrentThread (). GetName () + "can be from" +i+ "Library exit");p lace[i] = False;notifyall (); catch (Interruptedexception e) {e.printstacktrace ();}}}

Java Multi-threaded simulation parking problem

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.