1.第一种方式是常见的我们叫它等待唤醒方式吧
public class TestThreadCommunicate { public static void main(String[] args) { Communicate communicate = new Communicate(); new Thread(new Runnable() { @Override public void run(){ for (int i = 1; i <= 50; i++) { communicate.sub(); } } }).start(); for (int i = 1; i <= 10; i++) { communicate.main(); } } } class Communicate{ private boolean bool = true; public synchronized void sub() { while (!bool) { try { // 满足条件那么就等待,所以先不满足条件,等执行完后让子线程等待,主线程执行 this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("childThread......"); } bool = false; // 这个唤醒的是下一个线程 this.notify(); } public synchronized void main() { while (bool) { try { // 当执行完成后让主线程等,子线程执行 this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 50; j++) { System.out.println("mainThread......"); } bool = true; this.notify(); } }
代码执行过程:先让子线程执行,让主线程等待,等子线程执行完,让主线程执行,子线程等待。
2.使用Condition的方式
public class Condition { public static void main(String[] args) { Communicate communicate = new Communicate(); new Thread(new Runnable() { @Override public void run(){ for (int i = 1; i <= 50; i++) { communicate.sub(); } } }).start(); for (int i = 1; i <= 10; i++) { communicate.main(); } } static class Communicate{ private boolean bool = true; Lock lock = new ReentrantLock(); java.util.concurrent.locks.Condition condition = lock.newCondition(); public void sub() { lock.lock(); try { while (!bool) { try { // 满足条件那么就等待,所以先不满足条件,等执行完后让子线程等待,主线程执行 condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("childThread......"); } bool = false; condition.signal(); }finally { lock.unlock(); } } public void main() { lock.lock(); try { while (bool) { try { // 当执行完成后让主线程等,子线程执行 condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 50; j++) { System.out.println("mainThread......"); } bool = true; condition.signal(); }finally { lock.unlock(); } // this.notify(); } } }
这个是加锁机制,访问之前加锁,就如同第一个方式的wait。
当然还有其它的方式,自己看吧