【Java多线程】Java两个线程轮询打印A1B2C3
1.synchronized+wait()+notify()方式
static Object object = new Object(); public static void main(String[] args) { char[] num = "1234567".toCharArray(); char[] str = "ABCDEFG".toCharArray(); new Thread(() -> { synchronized (object) { for (char c : str) { try { System.out.println(Thread.currentThread().getName()+" = " + c); object.wait(); object.notify(); } catch (Exception e) { e.printStackTrace(); } } } }, "t1").start(); new Thread(() -> { synchronized (object) { for (char c : num) { try { System.out.println(Thread.currentThread().getName()+" = " + c); object.notify(); object.wait(); } catch (Exception e) { e.printStackTrace(); } } } }, "t2").start();
2.Lock+Condition 、await()+signal()
static Lock lock = new ReentrantLock(); static Condition condition = lock.newCondition(); public static void main(String[] args) { char[] num = "1234567".toCharArray(); char[] str = "ABCDEFG".toCharArray(); new Thread(()->{ lock.lock(); try { for (char c : str) { System.out.println(Thread.currentThread().getName()+" = " + c); condition.await(); condition.signal(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } },"t1").start(); new Thread(()->{ lock.lock(); try { for (char c : num) { System.out.println(Thread.currentThread().getName()+" = " + c); condition.signal(); condition.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } },"t2").start(); }
3.AtomicInteger原子类
static AtomicInteger thredNo=new AtomicInteger(1); public static void main (String[] args){ char[] num="1234567".toCharArray(); char[] str="ABCDEFG".toCharArray(); new Thread(()->{ for (char c : num) { //如果不是1就一直返回空,直到运行打印,打印完之后把原子对象变成2 while (thredNo.get()!=1){} System.out.println(c); thredNo.set(2); } },"t1").start(); new Thread(()->{ for (char c : str) { //如果不是2就一直返回空,直到运行打印,打印完之后把原子对象变成1 while (thredNo.get()!=2){} System.out.println(c); thredNo.set(1); } },"t1").start(); }
4.LockSupport
static Thread t1 ; static Thread t2 ; public static void main(String[] args) { char[] num = "1234567".toCharArray(); char[] str = "ABCDEFG".toCharArray(); t1 = new Thread(()->{ for (char c : num) { System.out.println(Thread.currentThread().getName()+"::::"+c); java.util.concurrent.locks.LockSupport.unpark(t2); java.util.concurrent.locks.LockSupport.park(); } },"t1"); t2 = new Thread(()->{ for (char c : str) { java.util.concurrent.locks.LockSupport.park(); System.out.println(Thread.currentThread().getName()+"::::"+c); java.util.concurrent.locks.LockSupport.unpark(t1); } },"t2"); t1.start(); t2.start(); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步