单例设计模式:
package com.thread;
public class Demo1_Singleton {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}
}
/*
* 饿汉式
class Singleton {
//1、私有构造方法,其他类不能访问该构造方法了
private Singleton() {}
//2.创建本类对象
private static Singleton s = new Singleton();
//3.对外提供公共的访问方法
public static Singleton getInstance() {
return s;
}
}
*/
/*
* 懒汉式,面试时候用 单例的延迟加载模式
*/
class Singleton {
//1、私有狗仔方法,其他类不能访问该构造方法了
private Singleton() {}
//2.创建本类对象
private static Singleton s;
//3.对外提供公共的访问方法
public static Singleton getInstance() {
if(s == null) {
s = new Singleton();
}
return s;
}
}
/*
* 饿汉式和懒汉式的区别
* 1.饿汉式式空间换时间,懒汉式式时间换空间
* 2.在多线程访问时,懒汉式不会创建多个对象,而懒汉式有可能会创建多个对象
*/
多线程(Timer)
package com.thread;
import java.util.Date;
import java.util.TimerTask;
public class Timer {
public static void main(String[] args) throws InterruptedException {
Timer t = new Timer();
//在指定时间安排指定任务
//第一个参数,是安排的任务,第二个参数是执行的时间,第三个参数是过多长时间在重复执行
t.schedule(new MyTimerTask(), new Date(188,6,1,14,22,50),3000);
while(true) {
Thread.sleep(1000);
System.out.println(new Date());
}
}
private void schedule(MyTimerTask myTimerTask, Date date, int i) {
}
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("起床");
}
}
线程通信
package com.thread;
public class Notify {
public static void main(String[] args) {
final Printer p = new Printer();
new Thread(){
public void run() {
while(true) {
p.print1();
}
}
}.start();
new Thread(){
public void run() {
while(true) {
p.print1();
}
}
}.start();
}
}
//等待唤醒机制
class Printer {
private int flag = 1;
public void print1() {
synchronized (this) { //同步方法只需要在方法上加synchronized关键字即可
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("\r\n");
}
}
public void print2() throws InterruptedException {
synchronized (this) {
if(flag != 1) {
this.wait();
}
System.out.println("5");
System.out.println("6");
System.out.println("7");
System.out.println("8");
System.out.println("\r\n");
}
}
}
class Demo {
}
sleep和wait 的区别
sleep方法必须传入参数,参数就是时间 时间到了自动醒来
wait方法可以传入参数也可以不传,传入参数就是在参数的时间结束后等待,不传入参数就是直接等待
sleep方法在同步函数或者同步代码块中,不释放锁
wait方法在同步函数或者同步代码块中,释放锁
线程的五种状态
stop已经过时
线程池
设计模式