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