1. 程式人生 > >24(多執行緒3)

24(多執行緒3)

1 單例設計模式

保證類在記憶體中只有一個物件。有三種寫法,下面分別介紹

(1)餓漢式

為什麼叫它餓漢式寫法呢,因為它在建立類的時候,不管三七二十一就直接建立了s物件,也不管s會不會被使用,相反,還有一種寫法叫懶漢式寫法。

(2)懶漢式(單例延遲載入模式)

多執行緒訪問會有安全隱患,所以開發不用

(3)無名氏

2 單例模式類之Runtime

3 單例模式類之Timer(計時器類)

4 多執行緒之間的通訊

package com.haidai.singleton;

public class Demo3 {

	public static void main(String[] args) {
		final Printer p = new Printer();

		new Thread() {
			@Override
			public void run() {
				while(true) {
					try {
						p.print1();
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
				}
			}

		}.start();

		new Thread() {
			@Override
			public void run() {
				while(true) {
					try {
						p.print2();
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
				}
			}
		}.start();

	}
}

class Printer {
	private int flag = 1;
	public void print1() throws InterruptedException {
		synchronized(this) {
			if(flag != 1) {
				this.wait();//當前執行緒睡
			}
			System.out.print("黑");
			System.out.print("馬");
			System.out.print("程");
			System.out.print("序");
			System.out.print("員");
			System.out.println();
			flag = 2;
			this.notify();//隨機叫醒一個執行緒
		}
	}

	public void print2() throws InterruptedException {
		synchronized(this) {
			if(flag != 2) {
				this.wait();
			}
			System.out.print("傳");
			System.out.print("智");
			System.out.print("播");
			System.out.print("客");
			System.out.println();
			flag = 1;
			this.notify();
		}
	}
}

5 執行緒的五種狀態