1.概念:
Thread 内部就是静态代理,Thread就是代理角色,Runnable就是真实角色
Thread 编码:
2. 线程状态:
新生状态:new Thread
就绪状态:start() 以后,等待cpu 调度
运行状态: cpu 调度以后
阻塞状态:
t3.join(); // 把t3线程执行完毕,在执行其他线层
Thread.yield(); //暂停自己线程,如果cpu有调度了main线程,那么继续执行main线程
Thread.sleep(50); // 暂停线程,指定时间
终止状态: 外部干涉自己定义boolean值
3. 线程Api
: t3.setName("我是小明"); // 设置线程名字
Thread.currentThread().getName(): 获取线程名字
// 可以设置线程优先级,不一定100%优先级提高了
t3.setPriority(Thread.MAX_PRIORITY); 10
t3.setPriority(Thread.NORM_PRIORITY); 5 (默认)
t3.setPriority(Thread.MIN_PRIORITY); 1
package com.denganzhi.pp;
class Web12306 implements Runnable{
private int num=50;
boolean isRunning=true;
@Override
public void run() {
while(isRunning) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(num<0) {
break; //跳出循环
}
System.out.println(Thread.currentThread().getName()+" 抢到了:"+num--);
}
}
public void setRunning(boolean isRuning) {
this.isRunning=isRuning;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Web12306 web12306=new Web12306();
Thread t3=new Thread(web12306);
t3.setName("我是小明"); // 设置线程名字
t3.start();
for (int i = 0; i < 20; i++) {
System.out.println("i==="+i);
System.out.println("线程状态:"+t3.isAlive());
if(i==2) {
//t3.join(); // 把t3线程执行完毕,在执行其他线层
//Thread.yield(); //暂停自己线程,如果cpu有调度了main线程,那么继续执行main线程
// 终止线程
web12306.setRunning(false);
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4. 单例设计模式
// 延迟加载 / “懒汉模式”
class Singleton {
// 将自身实例化对象设置为一个属性,并用static修饰
private static Singleton instance;
// 构造方法私有化
private Singleton() {}
// 静态方法返回该实例
public static Singleton getInstance() {
// 这里可能进来 2个线程, 线程 不安全的
// DCL双检查锁机制(DCL:double checked locking) 实现线程安全
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
// 立即加载 / “饿汉模式”
class Singleton2 {
// 如果类 没有 被加载, 那么浪费内存
// 优化
private static final Singleton2 instance = new Singleton2();
// 构造方法私有化
private Singleton2() {}
// 静态方法返回该实例
public static Singleton2 getInstance() {
return instance;
}
}
懒汉式存在线程安全问题,解决方法:
解决方法:https://www.cnblogs.com/binaway/p/8889184.html,DCL双检查锁机制
饿汉式优化:
class Singleton3 {
// 如果类 没有 用到 , 那么浪费内存
// 优化 , 调用SingletonJVMHolder.getInstance 才加载 new 中东西
private static class SingletonJVMHolder {
private static Singleton3 instance = new Singleton3();
}
// 构造方法私有化
private Singleton3() {}
// 静态方法返回该实例
public static Singleton3 getInstance() {
return SingletonJVMHolder.instance;
}
}