多线程可以分多条线程,同时执行程序,但也因此出现一些问题,通过线程锁可以解决
包子实例:
厨师做包子,顾客吃包子,多余50个包子厨师停止做包子,包子为零顾客停止吃包子,当厨师做到10个后顾客可以吃包子
顾客类 Customer.class
public class Customer implements Runnable {
Pack pack;
public Customer(Pack pack) {
this.pack = pack;
}
public void run() {
while (true) {
synchronized (pack) {
if (pack.num == 0) { //包子为0的时候顾客等待并唤醒厨师
try {
pack.notify();
pack.wait();
} catch (InterruptedException e) {
}
}
try {
Thread.sleep(200); //顾客0.2秒吃一个包子(线程睡眠200毫秒)
} catch (InterruptedException e) {
}
pack.num--;
System.out.println("顾客在吃包子,包子数量:" + pack.num);
}
}
}
}
厨师类 Cooker.class
public class Cooker implements Runnable {
Pack pack;
public Cooker(Pack pack) {
this.pack = pack;
}
public void run() {
while (true) {
synchronized (pack) { //增加线程锁,pake是钥匙
if (pack.num <= 50) { //包子小于50厨师做包子
if (pack.num >= 10) {
pack.notify(); //包子大于10个唤醒顾客
}
try {
Thread.sleep(1000); //1分钟做一个包子(线程睡眠一秒钟)
} catch (InterruptedException e) {
}
pack.num++;
System.out.println("厨师在做包子,包子数量:" + pack.num);
} else { //多于50个包子,厨师等待
try {
pack.wait();
} catch (InterruptedException e) {
}
}
}
}
}
}
包子类 Pack.class
public class Pack {
int num;
}
测试类 Test.class
public class Test {
public static void main(String[] args) {
Pack pack = new Pack(); //新建包子对象
pack.num = 50; //厨师包子数
//新建线程
Cooker cook = new Cooker(pack);
Thread thread1 = new Thread(cook);
Customer customer = new Customer(pack);
Thread thread2 = new Thread(customer);
//启动线程
thread1.start();
thread2.start();
}
}