package com.stock.test.base.thread; import com.stock.common.base.ResultVO; import org.junit.Test; import java.util.Collections; import java.util.concurrent.CountDownLatch; /** * * * 验证线程之间通信问题 * */ public class ThreadCommunicationTest { private static Integer index = 0; @Test public void test() throws InterruptedException { ResultVO lock1 = new ResultVO(); Thread thread1 = new Thread(new Runnable() { @Override public void run() { synchronized (lock1){ for(int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName()+"--->"+(++index)); if(index == 5){ System.out.println(Thread.currentThread().getName()+"----"+index); // 通知在对象锁的线程唤醒线程,进入可运行状态,但是必须等待当前线程执行完成,被唤醒的线程才会继续进行 lock1.notify(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } } },"t1"); Thread thread2 = new Thread(new Runnable() { @Override public void run() { synchronized (lock1){ try { if(index != 5 ){ System.out.println(Thread.currentThread().getName()+"--->"+index+"线程等待中......"); lock1.wait(); // 等待,并释放锁 } System.out.println(Thread.currentThread().getName()+"--->"+index+"线程停止"); } catch (InterruptedException e) { e.printStackTrace(); } } } },"t2"); thread2.start(); thread1.start(); Thread.sleep(10000000); } @Test public void testCountDownLatch() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); Thread thread1 = new Thread(new Runnable() { @Override public void run() { for(int i=0;i<=100;i++){ try { System.out.println(Thread.currentThread().getName()+"--->"+(++index)); Thread.sleep(500); if(index == 50){ countDownLatch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } } },"t1"); Thread thread2 = new Thread(new Runnable() { @Override public void run() { if(index != 50 ) { try { System.out.println(Thread.currentThread().getName() + "--->" + index + "线程等待中......"); countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"--->"+index+"线程停止"); } },"t2"); thread1.start(); thread2.start(); Thread.sleep(100000); Collections.synchronizedList(null); Collections.synchronizedMap(null); Collections.synchronizedSet(null); } }
2、线程之前通信
最新推荐文章于 2023-09-09 23:50:37 发布