蚂蚁吃蛋糕
package study;
class Cake implements Runnable{
int count = 10;
public void run() {
while(true) {
if(count>2) {
if(Thread.currentThread().getName().equals("一号")) {
eat();
}else if(Thread.currentThread().getName().equals("二号")) {
eat();
}
}else {
break;
}
}
}
public synchronized void eat() {
System.out.println(Thread.currentThread().getName()+"得到");
count=count-2;
}
}
public class Exercise {
public static void main(String[] args) {
Cake c = new Cake();
Thread t1 = new Thread(c,"一号");
Thread t2 = new Thread(c,"二号");
t1.start();
t2.start();
}
}
有100个窗口卖500张车票
package study;
import javax.sound.midi.Track;
class K395 implements Runnable{
int ticket=500;
int k=0,a=0;//a为车厢.k为号码
public void run() {
while(true) {
if(ticket==0) {
System.out.println("票已全部售完");
break;
}else{
buy();
}
}
}
public synchronized void buy() {
if(ticket>0) {
ticket--;
k++;
if(k==61) {
a++;
k=1;
}
System.out.println(Thread.currentThread().getName()+"售出一张车票,座位号是:"+a+"车厢"+k+"号, 还余"+ticket+"张票。");
}
}
}
public class exercise {
public static void main(String[] args) {
K395 k=new K395();
Thread[] T=new Thread[100];
for(int i=0;i<T.length;i++) {
T[i]=new Thread(k,"窗口"+i);
T[i].start();
}
}
}
到包子店买包子,但店家没有零钱
package study;
class Shop implements Runnable{
int five=0,ten=0,twenty=0;
public void run() {
if(Thread.currentThread().getName().equals("一号")) {
buy(20);
}else if(Thread.currentThread().getName().equals("二号")) {
buy(10);
}else if(Thread.currentThread().getName().equals("三号")) {
buy(5);
}if(Thread.currentThread().getName().equals("四号")) {
buy(5);
}
}
public synchronized void buy(int n){
if(n==5) {
five++;
System.out.println(Thread.currentThread().getName()+"得到了"+five+"***"+ten+"***"+twenty);
}else if(n==10) {
while(five<1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ten++;
five--;
System.out.println(Thread.currentThread().getName()+"得到了"+five+"***"+ten+"***"+twenty);
}else if(n==20) {
while(five<3 && !(five>=1 && ten>=1)) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(five>=3) {
five=five-3;
twenty++;
System.out.println(Thread.currentThread().getName()+"得到了"+five+"***"+ten+"***"+twenty);
}else if(five>=1&&ten>=1){
five--;
ten--;
twenty++;
System.out.println(Thread.currentThread().getName()+"得到了"+five+"***"+ten+"***"+twenty);
}
}
notifyAll();
}
}
public class Exercise {
public static void main(String[] args) {
Shop s = new Shop();
Thread t1 = new Thread(s, "一号");
Thread t2 = new Thread(s, "二号");
Thread t3 = new Thread(s, "三号");
Thread t4 = new Thread(s, "四号");
t1.start();
t2.start();
t3.start();
t4.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
/*
* thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。
* 比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
* join方法必须在线程start方法调用之后调用才有意义
*/
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}