Day25_多线程第二天

1、单例(掌握)

恶汉式
  1. class Singleton {
  2. //1,私有构造方法,其他类不能访问该构造方法了
  3. private Singleton(){}
  4. //2,创建本类对象
  5. private static Singleton s = new Singleton();
  6. //3,对外提供公共的访问方法
  7. public static Singleton getInstance() {//获取实例
  8. return s;
  9. }
  10. }

懒汉式
  1. class Singleton {
  2. //1,私有构造方法,其他类不能访问该构造方法了
  3. private Singleton(){}
  4. //2,声明一个引用
  5. private static Singleton s ;
  6. //3,对外提供公共的访问方法
  7. public static Singleton getInstance() {//获取实例
  8. if(s == null) {
  9. //线程1等待,线程2等待
  10. s = new Singleton();
  11. }
  12. return s;
  13. }
  14. }

饿汉式和懒汉式的区别
    1,饿汉式是空间换时间,懒汉式是时间换空间
    2,在多线程访问时,饿汉式不会创建多个对象,而懒汉式有可能会创建多个对象


2、JAVA通过命令执行Windows程序-Runtime


  1. public static void main(String[] args) throws Exception{
  2. //执行windows中的某些命令
  3. Process exec = Runtime.getRuntime().exec("arp -a");
  4. //获取控制台打印出的数据
  5. BufferedReader stream = new BufferedReader(new InputStreamReader(exec.getInputStream()));
  6. String line;
  7. while((line=stream.readLine()) != null){
  8. System.out.println(line);
  9. }
  10. }


3、定时器-Timer


  1. /*
  2. * void schedule(TimerTask 要执行的任务, Date 首次运行时间, long 每隔多久执行一次)
  3. */
  4. public static void main(String[] args) {
  5. //从当前时间开始执行,每隔1S执行一次
  6. new Timer().schedule(new TimerTask() {
  7. @Override
  8. public void run() {
  9. System.out.println("HEH");
  10. }
  11. }, new Date(),1000);
  12. }


4、线程之间的通信(多个线程共享同一数据的问题)


* 1.什么时候需要通信
* 多个线程并发执行时, 在默认情况下CPU是随机切换线程的
* 如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印
* 2.怎么通信
* 如果希望线程等待, 就调用wait()
* 如果希望唤醒等待的线程, 就调用notify();
* 这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用

  1. package com.heima.thread2;
  2. public class Demo1_Notify {
  3. /**
  4. * @param args
  5. * 等待唤醒机制
  6. */
  7. public static void main(String[] args) {
  8. final Printer p = new Printer();
  9. new Thread() {
  10. public void run() {
  11. while(true) {
  12. try {
  13. p.print1();
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }
  19. }.start();
  20. new Thread() {
  21. public void run() {
  22. while(true) {
  23. try {
  24. p.print2();
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }
  30. }.start();
  31. }
  32. }
  33. //等待唤醒机制
  34. class Printer {
  35. private int flag = 1;
  36. public void print1() throws InterruptedException {
  37. synchronized(this) {
  38. if(flag != 1) {
  39. this.wait(); //当前线程等待
  40. }
  41. System.out.print("黑");
  42. System.out.print("马");
  43. System.out.print("程");
  44. System.out.print("序");
  45. System.out.print("员");
  46. System.out.print("\r\n");
  47. flag = 2;
  48. this.notify(); //随机唤醒单个等待的线程
  49. }
  50. }
  51. public void print2() throws InterruptedException {
  52. synchronized(this) {
  53. if(flag != 2) {
  54. this.wait();
  55. }
  56. System.out.print("传");
  57. System.out.print("智");
  58. System.out.print("播");
  59. System.out.print("客");
  60. System.out.print("\r\n");
  61. flag = 1;
  62. this.notify();
  63. }
  64. }
  65. }


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, 这样就能区分唤醒的时候找哪个线程了
  1. package com.heima.thread2;
  2. import java.util.concurrent.locks.Condition;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. public class Demo3_ReentrantLock {
  5. /**
  6. * @param args
  7. */
  8. public static void main(String[] args) {
  9. final Printer3 p = new Printer3();
  10. new Thread() {
  11. public void run() {
  12. while(true) {
  13. try {
  14. p.print1();
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. }
  20. }.start();
  21. new Thread() {
  22. public void run() {
  23. while(true) {
  24. try {
  25. p.print2();
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. }.start();
  32. new Thread() {
  33. public void run() {
  34. while(true) {
  35. try {
  36. p.print3();
  37. } catch (InterruptedException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }
  42. }.start();
  43. }
  44. }
  45. class Printer3 {
  46. private ReentrantLock r = new ReentrantLock();
  47. private Condition c1 = r.newCondition();
  48. private Condition c2 = r.newCondition();
  49. private Condition c3 = r.newCondition();
  50. private int flag = 1;
  51. public void print1() throws InterruptedException {
  52. r.lock(); //获取锁
  53. if(flag != 1) {
  54. c1.await();
  55. }
  56. System.out.print("黑");
  57. System.out.print("马");
  58. System.out.print("程");
  59. System.out.print("序");
  60. System.out.print("员");
  61. System.out.print("\r\n");
  62. flag = 2;
  63. //this.notify(); //随机唤醒单个等待的线程
  64. c2.signal();
  65. r.unlock(); //释放锁
  66. }
  67. public void print2() throws InterruptedException {
  68. r.lock();
  69. if(flag != 2) {
  70. c2.await();
  71. }
  72. System.out.print("传");
  73. System.out.print("智");
  74. System.out.print("播");
  75. System.out.print("客");
  76. System.out.print("\r\n");
  77. flag = 3;
  78. //this.notify();
  79. c3.signal();
  80. r.unlock();
  81. }
  82. public void print3() throws InterruptedException {
  83. r.lock();
  84. if(flag != 3) {
  85. c3.await();
  86. }
  87. System.out.print("i");
  88. System.out.print("t");
  89. System.out.print("h");
  90. System.out.print("e");
  91. System.out.print("i");
  92. System.out.print("m");
  93. System.out.print("a");
  94. System.out.print("\r\n");
  95. flag = 1;
  96. c1.signal();
  97. r.unlock();
  98. }
  99. }



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:案例演示
线程组的使用,默认是主线程组

  1. MyRunnable mr = new MyRunnable();
  2. Thread t1 = new Thread(mr, "张三");
  3. Thread t2 = new Thread(mr, "李四");
  4. //获取线程组
  5. // 线程类里面的方法:public final ThreadGroup getThreadGroup()
  6. ThreadGroup tg1 = t1.getThreadGroup();
  7. ThreadGroup tg2 = t2.getThreadGroup();
  8. // 线程组里面的方法:public final String getName()
  9. String name1 = tg1.getName();
  10. String name2 = tg2.getName();
  11. System.out.println(name1);
  12. System.out.println(name2);
  13. // 通过结果我们知道了:线程默认情况下属于main线程组
  14. // 通过下面的测试,你应该能够看到,默任情况下,所有的线程都属于同一个组
  15. System.out.println(Thread.currentThread().getThreadGroup().getName());
  16. 自己设定线程组
  17. // ThreadGroup(String name)
  18. ThreadGroup tg = new ThreadGroup("这是一个新的组");
  19. MyRunnable mr = new MyRunnable();
  20. // Thread(ThreadGroup group, Runnable target, String name)
  21. Thread t1 = new Thread(tg, mr, "张三");
  22. Thread t2 = new Thread(tg, mr, "李四");
  23. System.out.println(t1.getThreadGroup().getName());
  24. System.out.println(t2.getThreadGroup().getName());
  25. //通过组名称设置后台线程,表示该组的线程都是后台线程
  26. 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
  1. // public static ExecutorService newFixedThreadPool(int nThreads)
  2. ExecutorService pool = Executors.newFixedThreadPool(2);
  3. // 可以执行Runnable对象或者Callable对象代表的线程
  4. pool.submit(new MyRunnable());
  5. pool.submit(new MyRunnable());
  6. //结束线程池
  7. pool.shutdown();


8、线程第三种创建方式(了解)

提交的是Callable
  1. // 创建线程池对象
  2. ExecutorService pool = Executors.newFixedThreadPool(2);
  3. // 可以执行Runnable对象或者Callable对象代表的线程
  4. Future<Integer> f1 = pool.submit(new MyCallable(100));
  5. Future<Integer> f2 = pool.submit(new MyCallable(200));
  6. // V get()
  7. Integer i1 = f1.get();
  8. Integer i2 = f2.get();
  9. System.out.println(i1);
  10. System.out.println(i2);
  11. // 结束
  12. pool.shutdown();
  13. public class MyCallable implements Callable<Integer> {
  14. private int number;
  15. public MyCallable(int number) {
  16. this.number = number;
  17. }
  18. @Override
  19. public Integer call() throws Exception {
  20. int sum = 0;
  21. for (int x = 1; x <= number; x++) {
  22. sum += x;
  23. }
  24. return sum;
  25. }
  26. }

多线程程序实现的方式3的好处和弊端
好处:
可以有返回值
可以抛出异常
弊端:
代码比较复杂,所以一般不用



5、等待唤醒机制

1、前提(掌握)
     两个线程共用一把锁,此时可以调用该锁的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、适配器模式(掌握

定义一个抽象类,该类将接口中的方法全部空实现
  1. package com.heima.适配器;
  2. public class Demo1_Adapter {
  3. /**
  4. * @param args
  5. * 适配器设计模式
  6. * 鲁智深
  7. */
  8. public static void main(String[] args) {
  9. }
  10. }
  11. interface 和尚 {
  12. public void 打坐();
  13. public void 念经();
  14. public void 撞钟();
  15. public void 习武();
  16. }
  17. abstract class 天罡星 implements 和尚 { //声明成抽象的原因是,不想让其他类创建本类对象,因为创建也没有意义,方法都是空的
  18. @Override
  19. public void 打坐() {
  20. }
  21. @Override
  22. public void 念经() {
  23. }
  24. @Override
  25. public void 撞钟() {
  26. }
  27. @Override
  28. public void 习武() {
  29. }
  30. }
  31. class 鲁智深 extends 天罡星 {
  32. public void 习武() {
  33. System.out.println("倒拔垂杨柳");
  34. System.out.println("拳打镇关西");
  35. System.out.println("大闹野猪林");
  36. System.out.println("......");
  37. }
  38. }

13、今天必须掌握的内容,面试题,笔试题。(掌握这个就可以放心学习后面的知识了)

1、说说单例设计模式
2、如何通过Java执行windows命令
3、Java中的定时器是哪个类
4、使用ReentrantLock的好处
5、说说简单工厂模式和工厂模式
6、说说适配器设计模式




posted on 2016-12-23 10:00  虫虫爬啊爬  阅读(186)  评论(0编辑  收藏  举报

导航