Day25_多线程第二天
1、单例(掌握)
恶汉式
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) {//线程1等待,线程2等待s = new Singleton();}return s;}}
饿汉式和懒汉式的区别
1,饿汉式是空间换时间,懒汉式是时间换空间
2,在多线程访问时,饿汉式不会创建多个对象,而懒汉式有可能会创建多个对象
2、JAVA通过命令执行Windows程序-Runtime
public static void main(String[] args) throws Exception{//执行windows中的某些命令Process exec = Runtime.getRuntime().exec("arp -a");//获取控制台打印出的数据BufferedReader stream = new BufferedReader(new InputStreamReader(exec.getInputStream()));String line;while((line=stream.readLine()) != null){System.out.println(line);}}
3、定时器-Timer
/** void schedule(TimerTask 要执行的任务, Date 首次运行时间, long 每隔多久执行一次)*/public static void main(String[] args) {//从当前时间开始执行,每隔1S执行一次new Timer().schedule(new TimerTask() {@Overridepublic void run() {System.out.println("HEH");}}, new Date(),1000);}
4、线程之间的通信(多个线程共享同一数据的问题)
* 1.什么时候需要通信
* 多个线程并发执行时, 在默认情况下CPU是随机切换线程的
* 如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印
* 2.怎么通信
* 如果希望线程等待, 就调用wait()
* 如果希望唤醒等待的线程, 就调用notify();
* 这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用
package com.heima.thread2;public class Demo1_Notify {/*** @param args* 等待唤醒机制*/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("程");System.out.print("序");System.out.print("员");System.out.print("\r\n");flag = 2;this.notify(); //随机唤醒单个等待的线程}}public void print2() throws InterruptedException {synchronized(this) {if(flag != 2) {this.wait();}System.out.print("传");System.out.print("智");System.out.print("播");System.out.print("客");System.out.print("\r\n");flag = 1;this.notify();}}}
5、1.5新特性
替换之前的同步代码块和等待唤醒方法
1、替换同步代码
创建ReentrantLock lock = new ReentrantLock
之前synchronized代码块被lock.lock();lock.unlock()替换
2、替换等待唤醒的方法,之前调用的是锁对象的wait() notify() notifyAll()方法 ,这三个方法都Object类里面的
通过newCondition对象
wait()方法被 await()替换
notify()方法被signal()替换
* 1.同步
* 使用ReentrantLock类的lock()和unlock()方法进行同步
* 2.通信
* 使用ReentrantLock类的newCondition()方法可以获取Condition对象
* 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
* 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
package com.heima.thread2;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class Demo3_ReentrantLock {/*** @param args*/public static void main(String[] args) {final Printer3 p = new Printer3();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();new Thread() {public void run() {while(true) {try {p.print3();} catch (InterruptedException e) {e.printStackTrace();}}}}.start();}}class Printer3 {private ReentrantLock r = new ReentrantLock();private Condition c1 = r.newCondition();private Condition c2 = r.newCondition();private Condition c3 = r.newCondition();private int flag = 1;public void print1() throws InterruptedException {r.lock(); //获取锁if(flag != 1) {c1.await();}System.out.print("黑");System.out.print("马");System.out.print("程");System.out.print("序");System.out.print("员");System.out.print("\r\n");flag = 2;//this.notify(); //随机唤醒单个等待的线程c2.signal();r.unlock(); //释放锁}public void print2() throws InterruptedException {r.lock();if(flag != 2) {c2.await();}System.out.print("传");System.out.print("智");System.out.print("播");System.out.print("客");System.out.print("\r\n");flag = 3;//this.notify();c3.signal();r.unlock();}public void print3() throws InterruptedException {r.lock();if(flag != 3) {c3.await();}System.out.print("i");System.out.print("t");System.out.print("h");System.out.print("e");System.out.print("i");System.out.print("m");System.out.print("a");System.out.print("\r\n");flag = 1;c1.signal();r.unlock();}}
6、线程组(了解)
A:线程组概述
Java中使用ThreadGroup来表示线程组,它可以对一批线程进行分类管理,Java允许程序直接对线程组进行控制。
默认情况下,所有的线程都属于主线程组。
public final ThreadGroup getThreadGroup()//通过线程对象获取他所属于的组
public final String getName()//通过线程组对象获取他组的名字
我们也可以给线程设置分组
1,ThreadGroup(String name) 创建线程组对象并给其赋值名字
2,创建线程对象
3,Thread(ThreadGroup?group, Runnable?target, String?name)
4,设置整组的优先级或者守护线程
B:案例演示
线程组的使用,默认是主线程组
MyRunnable mr = new MyRunnable();Thread t1 = new Thread(mr, "张三");Thread t2 = new Thread(mr, "李四");//获取线程组// 线程类里面的方法:public final ThreadGroup getThreadGroup()ThreadGroup tg1 = t1.getThreadGroup();ThreadGroup tg2 = t2.getThreadGroup();// 线程组里面的方法:public final String getName()String name1 = tg1.getName();String name2 = tg2.getName();System.out.println(name1);System.out.println(name2);// 通过结果我们知道了:线程默认情况下属于main线程组// 通过下面的测试,你应该能够看到,默任情况下,所有的线程都属于同一个组System.out.println(Thread.currentThread().getThreadGroup().getName());自己设定线程组// ThreadGroup(String name)ThreadGroup tg = new ThreadGroup("这是一个新的组");MyRunnable mr = new MyRunnable();// Thread(ThreadGroup group, Runnable target, String name)Thread t1 = new Thread(tg, mr, "张三");Thread t2 = new Thread(tg, mr, "李四");System.out.println(t1.getThreadGroup().getName());System.out.println(t2.getThreadGroup().getName());//通过组名称设置后台线程,表示该组的线程都是后台线程tg.setDaemon(true);
7、线程池(了解)
A:线程池概述
程序启动一个新线程成本是比较高的,因为它涉及到要与操作系统进行交互。而使用线程池可以很好的提高性能,尤其是当程序中要创建大量生存期很短的线程时,更应该考虑使用线程池。线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用。在JDK5之前,我们必须手动实现自己的线程池,从JDK5开始,Java内置支持线程池
B:内置线程池的使用概述
JDK5新增了一个Executors工厂类来产生线程池,有如下几个方法
public static ExecutorService newFixedThreadPool(int nThreads)
public static ExecutorService newSingleThreadExecutor()
这些方法的返回值是ExecutorService对象,该对象表示一个线程池,可以执行Runnable对象或者Callable对象代表的线程。它提供了如下方法
Future<?> submit(Runnable task)
<T> Future<T> submit(Callable<T> task)
使用步骤:
创建线程池对象
创建Runnable实例
提交Runnable实例
关闭线程池
C:案例演示
提交的是Runnable
// public static ExecutorService newFixedThreadPool(int nThreads)ExecutorService pool = Executors.newFixedThreadPool(2);// 可以执行Runnable对象或者Callable对象代表的线程pool.submit(new MyRunnable());pool.submit(new MyRunnable());//结束线程池pool.shutdown();
8、线程第三种创建方式(了解)
提交的是Callable
// 创建线程池对象ExecutorService pool = Executors.newFixedThreadPool(2);// 可以执行Runnable对象或者Callable对象代表的线程Future<Integer> f1 = pool.submit(new MyCallable(100));Future<Integer> f2 = pool.submit(new MyCallable(200));// V get()Integer i1 = f1.get();Integer i2 = f2.get();System.out.println(i1);System.out.println(i2);// 结束pool.shutdown();public class MyCallable implements Callable<Integer> {private int number;public MyCallable(int number) {this.number = number;}@Overridepublic Integer call() throws Exception {int sum = 0;for (int x = 1; x <= number; x++) {sum += x;}return sum;}}
多线程程序实现的方式3的好处和弊端
好处:
可以有返回值
可以抛出异常
弊端:
代码比较复杂,所以一般不用
5、等待唤醒机制
两个线程共用一把锁,此时可以调用该锁的wait和notify方法,实现等待唤醒机制
2、IllegalMonitorStateException异常原因及解决办法
如果当前的线程不是此对象锁的所有者,却调用该对象的notify(),notify(),wait()方法时抛出该异常
换句话说就是当前线程中的同步代码块的锁 和 调用这三个方法的锁对象不一致就会报错,例如
synchronized(Student.class){
Object.class.notify();
}
注意 必须有线程现在自食用Object.class锁
3、sleep和wait的区别(掌握)
wait:是Object类的方法,可以不用传递参数,释放锁对象sleep:是Thread类的静态方法,需要传递参数,不释放所对象
4、以下代码有没有问题
public synchronized void set(String name, int age) {if (this.flag) {try {Object.class.wait();} catch (Exception e) {}}this.name = name;this.age = age;this.flag = true;Object.class.notify();}
6、工厂模式(掌握)
创建对象的事情,可能比较复杂的,所以创建对象的这个逻辑我们应该定义到专门的一个类里面,这个类专门负责创建各种对象实例,那么这个类就被称为工厂类
简单工厂和工厂模式的区别
简单工厂:一个工厂可以创建多个对象,如果要添加对象,那应该修改工厂.简单工厂模式中的工厂类一般是使用静态方法,通过接收的参数的不同来返回2不同的对象实例。不修改代码无法扩展
工厂模式:一个工厂对应一个对象,换句话说 一个工厂只能创建一个对象,如果我要创建这个对象,第一步应该先创建工厂对象,然后通过工厂对象来创建对象。如果要添加对象,只需要再新增一个工厂即可,更符合开闭原则
比如说,我们现在有很多动物类,猫,狗,猪 ...
而这些动物有相同的行为, eat()。
抽取一个共同的父类。动物。
简单工厂模式:
Animal
|--Dog
|--Cat
AnimalFactory
public static Animal createAnimal(String type){
if("dog".equals(type)){
return new Dog();
}else if("cat".equals(type)){
return new Cat();
}else {
return null;
}
}
工厂方法模式:
Animal
|--Dog
|--Cat
|--Pig
AnimalFactory
|--DogFactory
|--CatFactory
|--PigFactory
7、适配器模式(掌握)
定义一个抽象类,该类将接口中的方法全部空实现
package com.heima.适配器;public class Demo1_Adapter {/*** @param args* 适配器设计模式* 鲁智深*/public static void main(String[] args) {}}interface 和尚 {public void 打坐();public void 念经();public void 撞钟();public void 习武();}abstract class 天罡星 implements 和尚 { //声明成抽象的原因是,不想让其他类创建本类对象,因为创建也没有意义,方法都是空的@Overridepublic void 打坐() {}@Overridepublic void 念经() {}@Overridepublic void 撞钟() {}@Overridepublic void 习武() {}}class 鲁智深 extends 天罡星 {public void 习武() {System.out.println("倒拔垂杨柳");System.out.println("拳打镇关西");System.out.println("大闹野猪林");System.out.println("......");}}
13、今天必须掌握的内容,面试题,笔试题。(掌握这个就可以放心学习后面的知识了)
1、说说单例设计模式
2、如何通过Java执行windows命令
3、Java中的定时器是哪个类
4、使用ReentrantLock的好处
5、说说简单工厂模式和工厂模式
6、说说适配器设计模式
浙公网安备 33010602011771号