Java 멀티스레딩 '대기/알림 메커니즘'
클래식 패러다임:
대기 파티는 다음 원칙을 따릅니다.
1. 물체의 자물쇠를 얻습니다.
2. 조건이 충족되지 않으면 객체의 wait() 메서드를 호출하고 알림을 받은 후에도 조건을 확인합니다.
3. 조건이 충족되면 해당 논리적 작업이 실행됩니다.
의사 코드는 다음과 같습니다.
synchronized(对象) { while(条件不满足) { 对象.wait(); } 完成任务逻辑 }
통지 당사자는 다음 원칙을 따릅니다.
1. 개체의 잠금을 얻습니다.
2. 조건을 변경하세요.
3. 개체를 대기 중인 모든 스레드에 알립니다.
의사 코드는 다음과 같습니다:
synchronized(对象) { 改变对象 对象.notifyAll(); }
샘플 코드:
import java.text.SimpleDateFormat;import java.util.Date;/** * 线程等待/通知机制 * Created by peng on 2018/7/22. */public class WaitNotify { private static boolean flag = true; private static Object lock = new Object(); public static void main(String[] args) { Thread waitThread = new Thread(new Wait(), "WaitThread"); waitThread.start(); SleepUtils.second(1); Thread notifyThread = new Thread(new Notify(), "NotifyThread"); notifyThread.start(); } private static class Wait implements Runnable { @Override public void run() { // 加锁,拥有lock的Monitor synchronized (lock) { // 当条件不满足时,继续wait,同时释放了lock的锁 while (flag) { try { System.out.println(Thread.currentThread() + " flag is true. wait @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 条件满足时,完成工作 System.out.println(Thread.currentThread() + " flag is false. running @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); } } } private static class Notify implements Runnable { @Override public void run() { // 加锁,拥有lock的Monitor synchronized (lock) { System.out.println(Thread.currentThread() + " hold lock. notify @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); lock.notifyAll(); flag = false; SleepUtils.second(5); } // 再次加锁 synchronized (lock) { System.out.println(Thread.currentThread() + " hold lock again. sleep @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); SleepUtils.second(5); } } } }
위 내용은 Java 멀티스레딩 '대기/알림 메커니즘'의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undress AI Tool
무료로 이미지를 벗다

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

XSLT 매개 변수는 외부 통과 값을 통한 동적 변환을위한 핵심 메커니즘입니다. 1. 선언 된 매개 변수를 사용하고 기본값을 설정하십시오. 2. xsltargumentList와 같은 인터페이스를 통해 응용 프로그램 코드 (예 : C#)에서 실제 값을 전달합니다. 3. 템플릿에서 $ paramname 참조 매개 변수를 통한 조건부 처리, 현지화, 데이터 필터링 또는 출력 형식 제어; 4. 모범 사례에는 의미있는 이름 사용, 기본값 제공, 관련 매개 변수 그룹화 및 값 확인이 포함됩니다. 매개 변수를 합리적으로 사용하면 XSLT 스타일 시트를 재사용 가능하고 유지 관리 가능하게 만들 수 있으며 동일한 스타일의 시트는 다양한 입력에 따라 다양한 출력 결과를 생성 할 수 있습니다.
![현재 NVIDIA GPU에 첨부 된 디스플레이를 사용하고 있지 않습니다 [고정].](https://img.php.cn/upload/article/001/431/639/175553352135306.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
ifyousee "YourEnotusingAdisplayAttachedToannvidiagpu,"YourMonitorIsConnectedTothenVidiagpupport, configuredisplaysettingsinnvidiacontrolpanel, updatedRiversUsingDduandcleanInstall, 및 setTheprestOdcreteinbios/uefi

Java 디자인 패턴은 일반적인 소프트웨어 설계 문제에 대한 재사용 가능한 솔루션입니다. 1. 싱글 톤 모드는 클래스의 인스턴스가 하나 뿐이며 데이터베이스 연결 풀링 또는 구성 관리에 적합합니다. 2. 공장 모드는 객체 생성을 분해하고 지불 방법과 같은 객체는 공장 클래스를 통해 생성됩니다. 3. 관찰자 모드는 날씨 업데이트와 같은 이벤트 중심 시스템에 적합한 종속 객체를 자동으로 알립니다. 4. 정렬 전략과 같은 전략 모드의 동적 스위칭 알고리즘은 코드 유연성을 향상시킵니다. 이러한 패턴은 코드 유지 관리 및 확장 성을 향상 시키지만 과도한 사용을 피해야합니다.

useOptional.empty (), 옵션.의 (), andoptional.ofnullable () theCreateOptionalInstancesDependingOnsabsent, non-null, orpossiblynull.2.checkforvaluessafelyusingispresent () orpreferlyinglioid () toaviDIDHECK.3

Adeadlockinjavaoccurswhentwoormorethreadsareblockedsforever,, 일반적으로, 일반적으로 duetocircularwaitcausedbyinconsentlockordering; thiscanbeptrededbectedbectedbectedbectedbectedbectefeartefournecessaryconditions —MutualExclusion, holdandwait, nopualwait, nopualclusion, nopualclusion
![운영 체제를 찾을 수 없습니다 [고정]](https://img.php.cn/upload/article/001/431/639/175539300224489.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
ifyourcomputershows "OperatingSystemnotFound,"TryTheSteps : 1. CheckBios/uefibootorder.2. VerifyDiskConnections.3.repairbootloaderusingwindowsrecovery.4.ReasignDriveDterViadiskManagement.5.reinstallthePeratingsystemecesssary.

theoilpaintfilterinphotoshopisgreyedoutus는 compatibledocumentoRlayertype를 incizeofindphotoshopcs6orlaterinthefulldesktopversion을 보장하고, mode 및 mouctipixureapioreapeLay ray를 확인합니다

micronautisidealforbuildingcloud-nativejavaapplicationsduetoitslowmemoryfootprint, faststartuptimes 및 compile-timedectional encection, mateituperiortotraditionalframslikespringbootformicroservices, andserverlessenvonderments.1.microna
