1_多线程(单例设计模式) *
单例设计模式:保证类在内存中只有一个对象。
如何保证类在内存中只有一个对象呢?
(1)控制类的创建,不让其他类来创建本类的对象。private
(2)在本类中定义一个本类的对象。Singleton s;
(3)提供公共的访问方式。 public static Singleton getInstance(){return s}
单例写法三种:
public class Demo5_Singleton {
//单列设计模式,保证类在内存中只有一个对象
public static void main(String[] args) {
Singleton s1 = Singleton.s; //成员变量私有,不能通过类名.调用,s和s1指向的是同一个对象
// Singleton.s = null;
Singleton s2 = Singleton.s;
System.out.println(s1 == s2); //比较引用地址值
/*Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);*/
}
}
//(1)饿汉式-简单直接-空间换时间-开发中使用
/*class Singleton {
//1.私有构造方法,其他类不能访问该构造方法
private Singleton() {}
//2.创建本类对象
public static Singleton s = new Singleton();
//3.对外提供公共的访问方法
public static Singleton getInstance() { //获取实例(对象)
return s;
}
}*/
//(2)懒汉式-单例延迟加载模式-时间换空间-开发不用
/*class Singleton {
//1.私有构造方法,其他类不能访问该构造方法
private Singleton() {}
//2.声明一个引用
public static Singleton s ;
//3.对外提供公共的访问方法
public static Singleton getInstance() { //获取实例(对象)
if(s == null) {
//线程1等待,线程2等待,有可能创建多个对象
s = new Singleton();
}
return s;
}
}*/
//(3)第三种格式-使用final修饰
class Singleton {
//1.私有构造方法,其他类不能访问该构造方法
private Singleton() {}
//2.声明一个引用
public final static Singleton s = new Singleton();
}
2_多线程(Runtime类)
Runtime类是一个单例类
import java.io.IOException;
public class Demo6_Runtime {
public static void main(String[] args) throws IOException {
Runtime r = Runtime.getRuntime(); //获取运行时对象
// r.exec("shutdown -s -t 3000");
r.exec("shutdown -a");
}
}
3_多线程(Timer) *
Timer类:计时器
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Demo7_Timer {
public static void main(String[] args) throws InterruptedException {
Timer t = new Timer();
//在指定时间安排指定任务:安排任务.执行时间.重复执行时间
//年=当前-1900 月=当前-1
t.schedule(new MytimerTask(), new Date(118, 9, 11, 11, 57, 30),3000);
while(true) {
Thread.sleep(1000);
System.out.println(new Date());
}
}
}
class MytimerTask extends TimerTask {
@Override
public void run() {
System.out.println("起床上班");
}
}
4_多线程(两个线程间的通信) *
1.什么时候需要通信
多个线程并发执行时, 在默认情况下CPU是随机切换线程的
如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印
2.怎么通信
如果希望线程等待, 就调用wait()
如果希望唤醒等待的线程, 就调用notify();
这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用
public class Demo8_Notify {
//等待唤醒机制
public static void main(String[] args) {
final Printer p = new Printer();
new Thread() {
public void run() {
while(true) {
try {
p.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
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("写");