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 线程的五种状态