Package Thread;
Import javax.xml.bind.ValidationEvent;
Class snacks{
private int saledsnacks=0;
private int totalsnacksnum=10; Initialize the snack bar starts with 10 loaves of bread
private int totaltimeofsale=0;
Public synchronized Boolean salesnacks () {
if (totalsnacksnum>0) {
saledsnacks++;
totalsnacksnum--;
totaltimeofsale++;
System.out.println (Thread.CurrentThread (). GetName () + "sell a loaf");
return true;
}else {
System.out.println ("Now sold out, need to wait until");
return false;
}
}
Public synchronized Boolean makesnacks () {
totalsnacksnum++;
totaltimeofsale+=3;
System.out.println (Thread.CurrentThread (). GetName () + "Make a loaf");
return true;
}
}
Class Salesnacks extends thread{
Private snacks snacks=new snacks ();
Public Salesnacks (String name,snacks s) {
Super (name);
Snacks=s;
}
public void Validation () {
while (Snacks.salesnacks ()) {
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
}
}
if (! Snacks.salesnacks ()) {
try {
Thread.Sleep (5000);
while (Snacks.salesnacks ()) {
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
}
}
} catch (Exception e) {
Todo:handle exception
}
}
Validation ();
}
@Override
public void Run () {
Validation ();
}
}
Class Makesnacks extends thread{
Private snacks snacks=new snacks ();
Public Makesnacks (String name,snacks s) {
Super (name);
Snacks=s;
}
@Override
public void Run () {
while (Snacks.makesnacks ()) {
try {
Thread.Sleep (3000);
} catch (Interruptedexception e) {
}
}
}
}
public class Thread_synchronized {
public static void Main (string[] args) throws Interruptedexception {
System.out.println ("Start selling snack!!! ");
Snacks Aimsnackshop=new Snacks ();
Salesnacks sale1=new salesnacks ("Windows:a", aimsnackshop);
Salesnacks sale2=new salesnacks ("Windows:b", aimsnackshop);
Salesnacks sale3=new salesnacks ("Windows:c", aimsnackshop);
Makesnacks makesnacks =new makesnacks ("Make:a", aimsnackshop);
Sale1.start ();
Sale2.start ();
Sale3.start ();
Makesnacks.start ();
try {
Thread.Sleep (500000);
} catch (Illegalthreadstateexception e) {
E.printstacktrace ();
}
}
}
Java thread learning the first day __ Low edition of the bread maker