倆個人吃蘋果( 加鎖 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;
}
}
}
}