兩個線程操作同一個資源,比如,輸入和輸出,操作同一個對象,此時兩個線程會爭奪cpu的執行權,隨機的進行切換。我們想實現先輸入再輸出,順序的執行
目標對象定義一個標記字段,進行判斷,wait()和notify()方法
wait()方法,線程會處於等待狀態,等待的線程位於內存中的線程池中
notify()方法,喚醒線程池中的線程
notifyAll()方法,喚醒全部線程
上面的方法,需要寫在同步裡面,並且需要標識鎖
這些操作線程的方法定義在Object對象中,因為這些方法,要通過同一個鎖對象來調用
/** * 資源 * * @author taoshihan * */ class People { String name; String sex; Boolean myLock = false; } /** * 輸入 * * @author taoshihan * */ class PeopleJoin implements Runnable { private People resource; public PeopleJoin(People resource) { this.resource = resource; } @Override public void run() { // 切換 boolean flag = true; while (true) { synchronized (resource) { if (resource.myLock) { try { resource.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (flag) { resource.name = "taoshihan"; resource.sex = "nan"; } else { resource.name = "陶士涵"; resource.sex = "男"; } flag = !flag; resource.myLock=true; resource.notify(); } } } } /** * 輸出 * * @author taoshihan * */ class PeopleOut implements Runnable { private People resource; public PeopleOut(People resource) { this.resource = resource; } @Override public void run() { while (true) { synchronized (resource) { if(!resource.myLock){ try { resource.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(resource.name + "=====" + resource.sex); resource.myLock=false; resource.notify(); } } } } public class ThreadDemo { /** * @param args */ public static void main(String[] args) { People resource = new People(); PeopleJoin input = new PeopleJoin(resource); PeopleOut output = new PeopleOut(resource); Thread t1 = new Thread(input); Thread t2 = new Thread(output); t1.start(); t2.start(); } }