Java Singleton 패턴을 구현하는 몇 가지 방법
이것은 몇 권의 책을 쓰는 것입니다.
공개 클래스 싱글 톤1 {private singleton1 () {} private static singleton1 인스턴스 = null; public static singleton1 getinstance () {if (instance == null) {instance = new Singleton1 (); } return 인스턴스; }}그러나 심각한 문제가 있기 때문에 이것은 실제 개발에 기록되지 않습니다. 다중 스레드 동시 액세스에 액세스 할 때 여러 인스턴스가 생성 될 수 있습니다! !
일반적으로 사용되는 몇 가지 방법은 다음과 같습니다.
1. 동기화 된 키워드를 사용하십시오
패키지 싱글 톤; 공개 클래스 싱글 톤1 {private singleton1 () {} private static singleton1 인스턴스 = null; // 다중 스레딩 문제의 솔루션 1이지만 효율적이지는 않습니다! 모든 전화가 잠겨 있기 때문에! public static synchronized singleton1 getinstance () {if (instance == null) {instance = new Singleton1 (); } return 인스턴스; } public void print () {system.out.println ( "Thread_id :"+thread.currentThread (). getId ()); } private static 객체 객체 = new Object (); // NULL이 추가 될 때만 매우 영리한 방법, 공개 static singleton1 getInstance2 () {if (instance == null) {synchronized (object) {instance = new Singleton1 (); }} return instance; }} 2. 잠금을 추가하십시오
패키지 싱글 톤; java.util.concurrent.locks.reentrantlock import; 공개 클래스 싱글 톤 2 {private singleton2 () {} private static reintrantlock lock = new ReintrantLock (); 개인 정적 singleton2 인스턴스 = null; public void print () {system.out.println ( "Thread_id :"+thread.currentthread (). getId ()); } public static singleton2 getInstance2 () {if (instance == null) {lock.lock (); if (instance == null) {// 여기에 또 다른 판단이 있습니다! ! 인스턴스 = New Singleton2 (); } lock.unlock (); } return 인스턴스; }} 3. 정적 변수 사용 :
패키지 싱글 톤; public class singleton3 {public static void print () {system.out.println ( "Thread_id :"+thread.currentThread (). getId ()); } public static nested getNested () {return nested.instance; } // 이것은 싱글 톤 정적 클래스 중첩으로 만든 클래스 {private nested () {} 정적 중첩 인스턴스 = New Nested (); }}위는 일반적으로 사용되는 싱글 톤 생성 패턴입니다.
테스트 테스트 코드 :
패키지 싱글 톤; Singleton.singleton3.nested 가져 오기; public class test2 {public static void main (String [] args) {// todo 자동 생성 메소드 스터브 중첩 된 싱글 톤; Myrunnable MM = New Myrunnable (); myrunnable m1 = 새로운 myrunnable (); myrunnable2 m2 = 새로운 myrunnable2 (); 새 스레드 (m1) .start (); 새 스레드 (m2) .start (); if (m1.singleton == m2.singleton) {// 그것은 동일한 system.out.println ( "동일하다"); } else {system.out.println ( "동일하지 않음"); }}} 클래스 myrunnable emplements runnable {중첩 싱글 톤; @override public void run () {// todo 자동 생성 메소드 스터브 싱글 톤 = singleton3.getnested (); Singleton3.print (); }} class myrunnable2는 런닝 가능한 {중첩 싱글 톤; @override public void run () {// todo 자동 생성 메소드 스터브 싱글 톤 = singleton3.getnested (); Singleton3.print (); }}산출:
동일합니다
Thread_id : 11
Thread_id : 10
위의 것은 Java Singleton 모델 정보의 편집입니다. 우리는 향후 관련 정보를 계속 추가 할 것입니다. 이 웹 사이트를 지원 해주셔서 감사합니다!