三亚市网站建设_网站建设公司_虚拟主机_seo优化
2026/1/17 7:54:28 网站建设 项目流程

Java 异步转同步方案

准备阶段
  • Student.java
publicclassStudent{publicvoidstudy(StudentStudyObserverstudentStudyObserver){newThread(()->{try{TimeUnit.SECONDS.sleep(5);}catch(InterruptedExceptione){e.printStackTrace();}studentStudyObserver.onFinish();}).start();}}
  • StudentStudyObserver.java
publicinterfaceStudentStudyObserver{voidonFinish();}
1、使用 CountDownLatch
CountDownLatchcountDownLatch=newCountDownLatch(1);Studentstudent=newStudent();student.study(()->{System.out.println("学生学习完了");countDownLatch.countDown();});try{countDownLatch.await();}catch(InterruptedExceptione){e.printStackTrace();}System.out.println("继续执行其他任务");
2、使用 CyclicBarrier
CyclicBarriercyclicBarrier=newCyclicBarrier(2);Studentstudent=newStudent();student.study(()->{System.out.println("学生学习完了");try{cyclicBarrier.await();}catch(InterruptedException|BrokenBarrierExceptione){e.printStackTrace();}});try{cyclicBarrier.await();}catch(InterruptedException|BrokenBarrierExceptione){e.printStackTrace();}System.out.println("继续执行其他任务");
3、使用 wait/notify + synchronized
privatevolatilebooleanfinished=false;
Objectlock=newObject();Studentstudent=newStudent();student.study(()->{synchronized(lock){System.out.println("学生学习完了");finished=true;lock.notify();}});try{synchronized(lock){while(!finished){lock.wait();}}}catch(InterruptedExceptione){e.printStackTrace();}System.out.println("继续执行其他任务");

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询