java学习总结:多线程(二)

本文介绍单例设计模式的两种实现方式:饿汉式和懒汉式,并对比它们的区别。此外,还介绍了Java中多线程的应用,包括定时任务的设置与线程间的通信机制。

单例设计模式:

在这里插入图片描述

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已经过时

线程池

在这里插入图片描述

设计模式

17350300911
在这里插入图片描述
在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值