Multi-threaded eating dumplings practice

Source: Internet
Author: User

Create a class with the Run method inheriting tread

public class Race {

public class Child extends thread{

private String name;

Private long time;

Private Plate p;

Public Child (String name,plate p,long time) {
THIS.name = name;
THIS.P = p;
This.time = time;
}

@Override
public void Run () {
TODO auto-generated Method Stub
int num = 0;
while (true) {
Synchronized (THIS.P) {
if (THIS.P.GETJZ () ==0) {
Break
}
num++;
This.p.setjiaozi (THIS.P.GETJZ ()-1);
System.out.println (THIS.name + "ate the first" + num + "Dumplings! ");
}
try {
Thread.Sleep (time);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}

Then create a method that can be used to pass the argument

public class Plate {

private int JZ = 25;

public int getjz () {
return JZ;
}

public void Setjiaozi (int jz) {
THIS.JZ = JZ;
}

}

To create a main method to run a thread

public class Eatjiaozi {

public static void Main (String[]args) {

Plate p = new Plate ();

Child C1 =new Child ("Z", p,2000);
Child C2 =new Child ("L", p,1500);

C1.start ();
C2.start ();
}
}

Multi-threaded eating dumplings practice

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.