package com.alpha;
class MyThread implements Runnable {
private int ticket = 5; // 一共有5张票
@Override
public void run() {
for (int i = 0; i < 20; i ++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName() + "卖票,ticket = " + this.ticket --);
}
}
}
}
public class MainClass { // 主类
public static void main(String[] args) throws Exception {
MyThread mt = new MyThread();
new Thread(mt, "票贩子A").start();
new Thread(mt, "票贩子B").start();
new Thread(mt, "票贩子C").start();
new Thread(mt, "票贩子D").start();
}
}
package com.alpha;
class Chinese {
public synchronized void say(Foreigner foreigner) {
System.out.println("把筷子给我,我给你刀叉。");
foreigner.get();
}
public synchronized void get() {
System.out.println("给出刀叉,得到筷子。");
}
}
class Foreigner {
public synchronized void say(Chinese chinese) {
System.out.println("把刀叉给我,我给你筷子。");
chinese.get();
}
public synchronized void get() {
System.out.println("给出筷子,得到刀叉。");
}
}
public class MainClass implements Runnable { // 主类
private Chinese chinese = new Chinese();
private Foreigner foreigner = new Foreigner();
public static void main(String[] args) throws Exception {
new MainClass();
}
public MainClass() {
new Thread(this).start();
chinese.say(foreigner);
}
@Override
public void run() {
foreigner.say(chinese);
}
}