本文旨在两个线程交替运行,不多哔哔直接看代码吧
public class Work2 { static final Object object = new Object(); public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { synchronized (object) { for (int i = 1; i < 10; i += 2) { System.out.println(Thread.currentThread().getName() + " " + i); object.notify(); try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { synchronized (object) { for (int i = 2; i < 10; i += 2) { System.out.println(Thread.currentThread().getName() + " " + i); object.notify(); try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }, "t2"); t1.start(); t2.start(); } }
该实现的原理也非常简单,定义一个对象,因为一个对象有且只有一个锁,所以让两个线程循环让此对象解锁->加锁,从而达到线程交替运行的目的;
个人觉得此方法还不够好,后续总结了再继续补充,还望看到的大佬们多指点指点!