public class Singleton {
//懒汉模式
//创建一个私有静态属性,并且把对象new出来
private static Singleton instance =new Singleton();
//私有化构造器
private Singleton() {
}
//提供一个公共的静态方法,返回单例对象
public static Singleton getInstance() {
return instance;
}
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true
}
}public class SingLetonLazy {
//创建一个对象不去new对象
private static SingLetonLazy instance;
//私有化构造器
private SingLetonLazy() {
}
//提供一个公共的静态方法,返回单例对象
public static SingLetonLazy getInstance() {
if(instance==null) {
instance=new SingLetonLazy();
}
return instance;
}
public static void main(String[] args) {
SingLetonLazy s1 = SingLetonLazy.getInstance();
SingLetonLazy s2 = SingLetonLazy.getInstance();
System.out.println(s1 == s2); // true
}
}public class SingLetonLazy {
private static SingLetonLazy instance;
//私有化构造器
private SingLetonLazy() {
}
//提供一个公共的静态方法,返回单例对象
public static SingLetonLazy getInstance() {
if(instance==null) {
instance=new SingLetonLazy();
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Thread t1 =new Thread(()->{
try {
sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
SingLetonLazy s1 = SingLetonLazy.getInstance();
System.out.println(s1);
});
t1.start();
}
}
}
出现了多线程问题。

public static SingLetonLazy getInstance() {
if(instance==null) {
synchronized (SingLetonLazy.class){
instance=new SingLetonLazy();
}
}
return instance;
}
public static SingLetonLazy getInstance() {
synchronized (SingLetonLazy.class){
if(instance==null) {
instance=new SingLetonLazy();
}
}
return instance;
}
private volatile static SingLetonLazy instance;
//给共享变量加上volatile
public static SingLetonLazy getInstance() {
//第一次判断是否加锁
if(instance==null) {
synchronized (SingLetonLazy.class) {
判断是否创建了一个对象
if (instance == null) {
instance = new SingLetonLazy();
}
}
}
return instance;
}



– 其中capacity是这个队列的大小。

– 这里设置一个三个大小的阻塞队列,当第四个元素入队时候就会发生阻塞等待

– 这里取出三个元素后,队列为空,队列阻塞等待


– put和take都会抛出一个InterrupteException异常

– add()

– offer()

– remove()

– poll


在这个模型中,服务器A要时刻感应到服务器B,在调用的过程中双方都要知道对方需要调用的参数和调用方式 ,在ABC整个调用的链路中秒如果其中一个出现了问题,就会影响整个业务执行



– 实例:

public class MyBlockingDeque {
int [] arr;
volatile int head=0;
volatile int tail=0;
volatile int size=0;
MyBlockingDeque(int capacity){
if(capacity<=0) {
throw new RuntimeException("capacity must be positive");
}
arr = new int[capacity];
}
public void put(int val) throws InterruptedException {
while(size>=arr.length) {
synchronized (this){
this.wait();
}
}
arr[tail]=val;
tail++;
if(tail>=arr.length) {
tail=0;
}
size++;
synchronized (this){
this.notifyAll();
}
}
public synchronized int take() throws InterruptedException {
while(size==0) {
this.wait();
}
int val =arr[head];
head++;
if(head>=arr.length) {
head=0;
}
size--;
this.notifyAll();
return val;
}
}
class Main{
public static void main(String[] args) throws InterruptedException {
MyBlockingDeque myBlockingDeque = new MyBlockingDeque(10);
int i=0;
new Thread(()->{
while (true){
try {
sleep(1000);
int val = myBlockingDeque.take();
System.out.println(Thread.currentThread().getName()+"取出成功"+val);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
while (true){
myBlockingDeque.put(i);
System.out.println(Thread.currentThread().getName()+"添加成功"+i);
i++;
}
}
}






import java.util.Timer;
import java.util.TimerTask;
public class Demo_801 {
public static void main(String[] args) {
// 使用jdk中提供的类,创建一个定器
Timer timer = new Timer();
//向定时器添加任务
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Hello World!");
}
},1000);
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("任务1");
}
},1500);timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("任务2");
}
},2000);timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("任务3");
}
},2500);
}
}ctrl+p查看方法的参数列表

定义自己的任务

延迟多久执行的任务

任务具体执行的时间





import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
public class MyTimer {
//用一个阻塞队列来组织任务
private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
private Object lock = new Object();
public MyTimer() {
//创建线程
Thread thread =new Thread(()->{
while(true){
try {
//从队列中取出任务
MyTask task=this.queue.take();
//判断有没有到执行的时间
long currentTime=System.currentTimeMillis();
if(currentTime>=task.getTime()){
//时间到了执行
task.getRunnable().run();
} else{
//时间没到,将任务放回队列中
this.queue.put(task);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
}
/**
* 添加定时任务
* @param runnable 任务
* @param delay 延时
* @throws InterruptedException
*/
public void schedule(Runnable runnable,long delay) throws InterruptedException {
//根据传的参数构造一个MyTask对象
MyTask task=new MyTask(runnable,delay);
//将这个MyTask对象阻塞放入队列中
queue.put(task);
}
}
//MyTask类,用于封装任务和执行时间
class MyTask implements Comparable<MyTask>{
//任务
private Runnable runnable;
//执行时间
private long time;
public MyTask(Runnable runnable, long delay) {
//增强代码健壮性
if(runnable==null){
throw new IllegalArgumentException("任务不能为空");
}
if(delay<0) {
throw new IllegalArgumentException("延迟时间不能为负数");
}
this.runnable = runnable;
//计算出任务的执行时间
this.time = delay+System.currentTimeMillis();
}
public Runnable getRunnable() {
return runnable;
}
public long getTime() {
return time;
}
@Override
public int compareTo(MyTask o) {
if(this.getTime()<o.getTime()){
return -1;
} else if(this.getTime()==o.getTime()){
return 0;
}else {
return 1;
}
//万一时间超过了long的范围溢出,怎么办?用上面的比较比较好
//return (int)(this.getTime()-o.getTime());
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyTimer timer = new MyTimer();
timer.schedule(new Runnable(){
@Override
public void run() {
System.out.println("任务1");
}
},1000);
timer.schedule(new Runnable(){
@Override
public void run() {
System.out.println("任务2");
}
},500);
timer.schedule(new Runnable(){
@Override
public void run() {
System.out.println("任务3");
}
},2000);
//timer.schedule(null,-100);
//任务加强健壮性
}
}

– 我们要添加校验,防止非法的输入

– 解决数据可能会溢出的问题,比如设置的时间



– 这里注意一下这个lambda表达式中的this引用的是他所在对象的实例。

每添加新的任务都进行一次唤醒,保证执行的永远是最少延时的任务。

这个线程造成的原因就是没有保证原子性。



– 我们发现当我们把三个任务的延时时间设置为0的时候,结果只执行了任务1,我们进行调试

– 调试之后我们又发现是正常情况,但是运行时候不符合我们的预期结果,这时候我们不要慌,我们用jconsole工具去查看下扫描情况


1.创建一个定时器 2.向定时器添加任务1 3.第一个任务被添加到阻塞队列中 4.扫描线程启动,处理第一个任务 5.扫描线程1循环,获得第二个任务时候,队列为空,开始等待,同时扫描线程获得锁 6.主线程向阻塞队列添加任务时候,等待扫描对象的对象,由于扫描线程无法释放锁对象,主线程也就获取不到锁对象,造成相互等待,造成死锁

-最终的代码
public class MyTimer {
//用一个阻塞队列来组织任务
private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
private Object lock = new Object();
public MyTimer() {
//创建线程
Thread thread =new Thread(()->{
while(true) {
try {
synchronized (this) {
//从队列中取出任务
MyTask task = this.queue.take();
//判断有没有到执行的时间
long currentTime = System.currentTimeMillis();
if (currentTime >= task.getTime()) {
//时间到了执行
task.getRunnable().run();
} else {
//时间没到,将任务放回队列中
long waitTime = task.getTime() - currentTime;
this.queue.put(task);
this.wait(waitTime);
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
//创建守护线程,定时唤醒一次
Thread deamonThread=new Thread(()->{
synchronized (this) {
//唤醒一次
this.notifyAll();
//每隔100ms唤醒一次
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
//设置为守护线程
deamonThread.setDaemon(true);
deamonThread.start();
}
/**
* 添加定时任务
* @param runnable 任务
* @param delay 延时
* @throws InterruptedException
*/
public void schedule(Runnable runnable,long delay) throws InterruptedException {
//根据传的参数构造一个MyTask对象
MyTask task=new MyTask(runnable,delay);
//将这个MyTask对象阻塞放入队列中
queue.put(task);
System.out.println("任务添加成功");
}
}
//MyTask类,用于封装任务和执行时间
class MyTask implements Comparable<MyTask>{
//任务
private Runnable runnable;
//执行时间
private long time;
public MyTask(Runnable runnable, long delay) {
//增强代码健壮性
if(runnable==null){
throw new IllegalArgumentException("任务不能为空");
}
if(delay<0) {
throw new IllegalArgumentException("延迟时间不能为负数");
}
this.runnable = runnable;
//计算出任务的执行时间
this.time = delay+System.currentTimeMillis();
}
public Runnable getRunnable() {
return runnable;
}
public long getTime() {
return time;
}
@Override
public int compareTo(MyTask o) {
if(this.getTime()<o.getTime()){
return -1;
} else if(this.getTime()==o.getTime()){
return 0;
}else {
return 1;
}
//万一时间超过了long的范围溢出,怎么办?用上面的比较比较好
//return (int)(this.getTime()-o.getTime());
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyTimer timer = new MyTimer();
timer.schedule(new Runnable(){
@Override
public void run() {
System.out.println("任务1");
}
},0);
timer.schedule(new Runnable(){
@Override
public void run() {
System.out.println("任务2");
}
},0);
timer.schedule(new Runnable(){
@Override
public void run() {
System.out.println("任务3");
}
},0);
//timer.schedule(null,-100);
//任务加强健壮性
}
}
我们这里造成了重载参数的相同,但是我们就是要这样的构造方法我们怎么解决呢?

工厂方法模式。根据不同的业务需求定义不同的方法来获取对象。
public static void main(String[] args) {
//1.用来处理大量短时间的任务的线程池,如果池没有可用的线程将创建线程,如果线程空闲60秒将收回并移除缓存
ExecutorService cachedThreadpool= Executors.newCachedThreadPool();
//2.创建一个操作无界队列,线程池大小固定的线程池
ExecutorService fixedThreadpool= Executors.newFixedThreadPool(5);//可以指定线程数量
//3.创建一个操作无界队列,只有一个线程的线程池
ExecutorService singleThreadExecutor= Executors.newSingleThreadExecutor();
//4.创建一个单线程执行器,可以加时间给定时间后执行或者定期执行
ScheduledExecutorService singleThreadScheduledExecutor= Executors.newSingleThreadScheduledExecutor();
//5.创建一个指定大小的线程池,可以加时间给定时间后执行或者定期执行
ScheduledExecutorService scheduledThreadpool= Executors.newScheduledThreadPool(5);
//6.创建一个指定大小(不传参,为当前机器的cpu核数)的线程池,并行处理任务,不保证处理顺序
Executors.newWorkStealingPool();
}Runtime.getRuntime().availableProcessors()
获取系统的cpu核数public class MyExectorService {
//定义阻塞队列阻止任务
private BlockingQueue<Runnable> queue=new LinkedBlockingQueue(100);
private static Object lock=new Object();
public MyExectorService(int threadNum){
for (int i = 0; i < threadNum; i++){
Thread thread=new Thread(()->{
//不停扫描队列
while (true) {
try {
synchronized (lock){
Runnable runable= queue.take();
runable.run();
}
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}//take()方法会阻塞,直到队列中有任务
});
//启动线程
thread.start();
}
}
/**
* 提交任务到线程池中
* @param runnable 具体的任务
* @throws InterruptedException
*/
public void sumbit(Runnable runnable) throws InterruptedException {
if(runnable==null){
throw new IllegalArgumentException("任务不能为空");
}
//把任务加入队列中
queue.put(runnable);
}
}
class Test1{
public static void main(String[] args) throws InterruptedException {
MyExectorService myExectorService=new MyExectorService(3);
AtomicInteger j= new AtomicInteger();
for (int i = 0; i < 10; i++) {
myExectorService.sumbit(() -> {
System.out.println(Thread.currentThread().getName() + " " + j);
j.getAndIncrement();
});
if(i%3==0){
TimeUnit.SECONDS.sleep(1);
}
}
}
}

用现实的两个例子去模拟线程工作的原理 周末去吃饭

银行办理业务



public static void main(String[] args) {
ThreadPoolExecutor threadPool=new ThreadPoolExecutor(
2,5,10, TimeUnit.SECONDS
,new LinkedBlockingQueue<>(7)
,new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 100; i++) {
int takeI=i;
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 执行任务 "+takeI);
}
});
}
}

public static void main(String[] args) {
ThreadPoolExecutor threadPool=new ThreadPoolExecutor(
2,5,10, TimeUnit.SECONDS
,new LinkedBlockingQueue<>(7)
,new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 100; i++) {
int takeI=i;
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 执行任务 "+takeI);
}
});
}
}
public static void main(String[] args) {
ThreadPoolExecutor threadPool=new ThreadPoolExecutor(
2,5,10, TimeUnit.SECONDS
,new LinkedBlockingQueue<>(7)
,new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 0; i < 100; i++) {
int takeI=i;
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 执行任务 "+takeI);
}
});
}
}
public static void main(String[] args) {
ThreadPoolExecutor threadPool=new ThreadPoolExecutor(
2,5,10, TimeUnit.SECONDS
,new LinkedBlockingQueue<>(7)
,new ThreadPoolExecutor.DiscardPolicy());
for (int i = 0; i < 100; i++) {
int takeI=i;
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 执行任务 "+takeI);
}
});
}
}
1.共同点,让线程休眠一会 2.从实现使用上来说是两种不同的方法 wait是Object类的方法,与锁相关,配合sychronized一起使用,调用wait之后会释放锁 sleep是Thread类的方法,与锁无关 wait可以通过notify和指定直线的方法唤醒,唤醒之后重新竞争锁资源 sleep只能通过超时时间唤醒
