俩个人吃苹果( 加锁 synchronized 和wait,notify/notifyall一起用 )
public class Text05 {
public static void main(String[] args) {
Runnable3 runnable3 = new Runnable3();
Thread thread = new Thread(runnable3);
thread.start();
Thread thread_b = new Thread(runnable3);
thread_b.start();
}
}
//俩个人吃苹果 俩秒吃一个 100个
class Runnable3 implements Runnable{
int apple = 100; //共享的变量
@Override//重写run方法,子线程执行的方法写在run里面
public void run() {
while (true) {
//锁里面的代码只能有一个线程执行
synchronized (this) {
if (apple>0) {
//加锁
apple--;
System.out.println(Thread.currentThread().getName()+"吃了苹果,剩下"+apple+"个");
//解锁
}else {
break;
}
}
}
}
}
运行结果:谁先抢到谁先吃,随机
方法二的加锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Text06 {
public static void main(String[] args) {
Runnable4 runnable4 = new Runnable4();
Thread thread = new Thread(runnable4);
thread.start();
Thread thread1 = new Thread(runnable4);
thread1.start();
}
}
//俩个人吃一个苹果 俩秒吃一个 100
class Runnable4 implements Runnable{
int apple =100;
final Lock lock = new ReentrantLock();
@Override
//重写run方法 子线程执行的方法写在run里面
//public syncgronized void run(){//锁住函数 同一时刻 只能由一个线程来调用
public void run() {
while (true) {
lock.lock();//加锁
if (apple>0) {
apple--;
System.out.println(Thread.currentThread().getName()+"吃了苹果,剩下"+apple+"个");
lock.unlock();//解锁
}else{
break;
}
}
}
}