zoukankan      html  css  js  c++  java
  • 2019-06-04 Java学习日记 day25 多线程下

    单例设计模式

      保证设计模式:保证类在内存只有一个对象

    如何保证泪在内存中只有一个对象

      控制类打的创建,不让其他类来创建本类的对象。private

      在本类重定义一个本类的对象。Singleton s;

      提供公共的访问方法,public static Singleton getInstance(){return s}

     

    1.饿汉式 开发用这种方式

    2.懒汉式 面试写这种方式

    饿汉式是空间换时间,懒汉式是时间换空间

    在多线程访问时,饿汉式不会创建多个对象,而懒汉式有可能会创建多个对象

    public class demo1_Singleton {
    
        public static void main(String[] args) {
            //Singleton s1=new Singleton();  成员变量被私有化,不能直接调用
            //Singleton s1=Singleton.s;
            //Singleton s2=Singleton.s;
            //System.out.println(s1 ==s2);
            
            Singleton s1=Singleton.getInstance();
            Singleton s2=Singleton.getInstance();
            
            System.out.println(s1 == s2);
    
        }
    
    }
    /*//饿汉式
    class Singleton{
        //私有构造方法,其他类不能访问该构造方法了
        private Singleton(){}
        //创建类对象
         private  static Singleton s= new Singleton();
         //对外提供公共的访问方法
         public static Singleton getInstance(){ //获取实例
             return s;
         }
    }*/
    
    //懒汉式,单例的延迟加载模式
    class Singleton{
        //私有构造方法,其他类不能访问该构造方法了
        private Singleton(){}
        //创建类对象
         private  static Singleton s= new Singleton();
         //对外提供公共的访问方法
         public static Singleton getInstance(){ //获取实例
             if (s==null) {
                s =new Singleton();
            }
             return s;
         }
    }
    案例

    多线程(Runtime类)

      *Runtime类是一个单例类

    public class demo2_Runtime {
    
        public static void main(String[] args) throws IOException {
            Runtime r1=Runtime.getRuntime();
            //r1.exec("shutdown -s -t 300");
            r1.exec("shutdown -a");
    
        }
    
    }
    案例

    Timer:计时器

    year -减 1900 的年份

    month - 0-11 之间的月份

    date - 一月中1-3 之间的某一天

    hrs - 0-23 之间的小时数

    min - 0-59 之间的分钟数

    sec - 0-59 之间的秒数

    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class demo3_Timer {
    
        /**
         * @param args
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws InterruptedException {
            Timer t = new Timer();
            //在指定时间安排指定任务
            //第一个参数,是安排的任务,第二个参数是执行的时间,第三个参数是过多长时间再重复执行
            t.schedule(new MyTimerTask(), new Date(119, 5, 5, 0, 30, 10),3000);    
            
            while(true) {
                Thread.sleep(1000);
                System.out.println(new Date());
            }
        }
    
    }
    
    class MyTimerTask extends TimerTask {
    
        @Override
        public void run() {
            System.out.println("要起床了");
        }
    }
    案例

    两个线程间的通信

      多个线程并发执行时,在默认情况下CPU是随机切换线程的

      如果我们希望他们有规律的执行,就可以使用通信,例如每个线程执行一次打印

    怎么通信

      如果希望线程等待,就调用wait()

      如果希望唤醒等待的线程,就调用notify()

      这两个方法必须再同步代码中执行,并且使用同步锁对象来调用

    public class demo1_Notify {
    
        public static void main(String[] args) {
            printer p1=new printer();
            new Thread(){
                public void run(){
                    while(true){
                        try {
                            p1.print1();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
            new Thread(){
                public void run(){
                    while(true){
                        try {
                            p1.print2();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            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("子");
            System.out.print("
    ");
            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("真");
            System.out.print("好");
            System.out.print("
    ");
            flag =1;
            this.notify();
        }
     }
    }
    案例

    三个或以三个以上间的线程通信

     *多个线程通信的问题

      *notify()方法时随机唤醒一个线程

      *notifyAll()方法时唤醒所有线程

      *JDK5之前无法唤醒指定的一个线程

      *如果多个线程之间通信,需要使用notifyAll()通知所有线程,用while来反复判断条件

     1.在同步代码块中,用哪个对象锁,就用哪个对象调用wait方法

     2.为什么wait方法和notify方法定义object这类中

      因为锁对象可以是任意对象,object是所有的类的基类,所以wait方法和notify方法需要定义在objcect这个类中

     3.sleep方法和wait方法的区别

      *sleep方法必须传入参数,参数就是时间,时间到了自动醒来

        wait方法可以传入参数也可以不传入参数,传入参数就是在参数的时间结束后等待,不传入参数就是直接等待

      *sleep方法再同步函数或同步代码块中,不释放锁

        wait方法在同步函数或者同步代码中,释放锁

    jdk1.5的新特性互斥锁

    同步

      使用ReentrantLock类的lock()和unlock()方法进行同步

    通信

      使用ReentrantLock类的newCondition()方法可以获取Condition对象

      需要等待的时候使用Condition的await()方法,唤醒的时候用signal()方法

      不同的线程使用不同的Condition,这样就能区分唤醒的时候找哪个线程了

    public class demo3_ReentrantLock {
    
        public static void main(String[] args) {
            final printer3 p1=new printer3();
            new Thread(){
                public void run(){
                    while(true){
                        try {
                            p1.print1();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
            new Thread(){
                public void run(){
                    while(true){
                        try {
                            p1.print2();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
    
            new Thread(){
                public void run(){
                    while(true){
                        try {
                            p1.print3();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            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 != 3) {
                c1.await();
            }
        System.out.print("i");
        System.out.print("t");
        System.out.print("h");
        System.out.print("a");
        System.out.print("a");
        System.out.print("i");
        System.out.print("
    ");
        flag =1;
        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("真");
        System.out.print("好");
        System.out.print("
    ");
        flag =3;
        c3.signalAll();
        r.unlock();
    }
    public void print3() throws InterruptedException{
            r.lock();
            if (flag !=1) {
                c3.await();//当前线程等待
            }
        System.out.print("明");
        System.out.print("天");
        System.out.print("是");
        System.out.print("好");
        System.out.print("日");
        System.out.print("子");
        System.out.print("
    ");
        flag=2;
        c1.signalAll();
        r.unlock();
    
    }    
    
    }
    案例

    线程组概述

      Java中使用ThreadGroup来表示线程组,它可以对一批线程进行分类管理,Java允许程序直接对线程组进行控制

      默认情况下,所有的线程都属于主线程组

        public final ThreadGroup getThreadGroup() //通过线程对象获取他所属于的组

        public final String getName() //通过线程组对象获取他组的名字

      我们也可以给线程设置分组

        ThreadGroup(String name)创建线程组对象并给赋值名字

        创建线程对象

        Thread(ThreadGroup?group,Runnable?target,String?name)

        设置整租的优先级或者守护线程

    public class demo4_ThreadGroup {
    
        public static void main(String[] args) {
            //demo1();
            ThreadGroup tg =new ThreadGroup("我是新的");  //创建新的线程组
            MyRunnable m1 = new MyRunnable();            //创建Runnable的子类对象
            Thread t1 =new Thread(tg,m1,"三");            //将线程t1放在组中
            Thread t2 =new Thread(tg,m1,"二");
            System.out.println(t1.getThreadGroup().getName());  //获取组名
            System.out.println(t2.getThreadGroup().getName());
            tg.setDaemon(true);
    
        }
    
        public static void demo1() {
            MyRunnable m1=new MyRunnable();
            Thread t1 =new Thread("三");
            Thread t2=new Thread("二");
            
            ThreadGroup tg1 =t1.getThreadGroup();
            ThreadGroup tg2=t1.getThreadGroup();
            
            System.out.println(tg1.getName());  //默认是主线程
            System.out.println(tg2.getName());
        }
    
    }
    class MyRunnable implements Runnable{
    
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.out.println(Thread.currentThread().getName()+"...."+i);
            }
            
        }
        
    }
    案例

    线程的五种状态

      线程的生命周期:    

        新建 创建线程对象

        就绪 线程对象已经启动了,但是还没有获取到 CPU 的执行权

           运行 获取到了CPU的执行权

          阻塞:没有CPU的执行权 回到就绪

        死亡 代码运行完毕,线程死亡

    线程池概述

      程序启动一个新线程成本是比较高的,因为它涉及到要与操作系统进行交互。而使用线程池可以很好的提高性能,尤其是当程序中药创建大量生存期很短的线程时,更应该考虑使用线程池。线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用,在JDK5之前,我们必须手动显示自己的线程池,从JDK5开始,Java内置支持线程池

    内置线程池的使用

      JDK新增了一个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实例

      关闭线程池

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class demo5_Executors {
    
        public static void main(String[] args) {
            ExecutorService e1=Executors.newFixedThreadPool(2);
            e1.submit(new MyRunnable()); //蒋贤成放池子里并执行
            e1.submit(new MyRunnable());
            
            e1.shutdown();//关闭线程池
        }
    
    }
    案例

    多线程实现方式

    public class demo6_Callable {
    
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            ExecutorService e1=Executors.newFixedThreadPool(2);
            Future<Integer> f1=e1.submit(new mycallable(100)); //蒋贤成放池子里并执行
            Future<Integer> f2=e1.submit(new mycallable(50));
            
            System.out.println(f1.get());
            System.out.println(f2.get());
            e1.shutdown();//关闭线程池
    
        }
    
    }
    class mycallable implements Callable<Integer>{
        private int num;
        public mycallable(int num){
            this.num =num;
        }
        
        public Integer call() throws Exception {
            
            int sum =0;
            for (int i = 1; i <= num; i++) {
                sum+=i;
            }
            return sum;
        }
        
    }
    案例

    简单工厂模式

      又叫静态工厂方法模式,它定义一个具体的工厂类服装创建一些类的实例

    优点:

      客户端不需要再服装对象的创建,从而明确了各个类的职责

    缺点:

      这个静态静态工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,就需要不断的修改工厂类,不利于后期维护

    public abstract class animal {
        public abstract void eat();
    }
    
    
    public class dog extends animal {
    
        public void eat() {
            System.out.println("狗吃肉");
    
        }
    
    }
    
    
    public class Cat extends animal {
    
        public void eat() {
            System.out.println("猫吃鱼");
    
        }
    
    }
    
    
    
    
    public class AnimalFactoy {
        /*public static dog eatdog(){
            return new dog();
        }
        public static Cat eatcat(){
            return new Cat();
        }*/
        
        public static animal createAnimal(String name){
            if ("dog".equals(name)) {
                return new dog();
            }else if ("cat".equals(name)) {
                return new Cat();
            }else {
                return null;
            }
        }
    }
    
    
    
    public class Test1 {
    
        public static void main(String[] args) {
            //dog d1=AnimalFactoy.eatdog();
            dog d1=(dog)AnimalFactoy.createAnimal("dog");
            d1.eat();
    
        }
    
    }

    工厂方法模式

      工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现

    优点:

      客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性

    缺点:

      需要额外的编写代码,增加了工作量

    Graphical User Interface(图形用户接口)

    public class demo1_Frame {
    
        public static void main(String[] args) {
            Frame f1 = new Frame("QQ");
            f1.setSize(400,600);//大小
            f1.setLocation(600, 50);//位置
            f1.setIconImage(Toolkit.getDefaultToolkit().createImage("dog.jpg"));//图标
            f1.setVisible(true);
            
        }
    
    }
    案例

    布局管理器

     FlowLayout(流式布局管理器)

      *从左到右的顺序排列

      *Panel默认的布局管理器

     BorderLayout(边界布局管理器)

      *东,南,西,北,中

      *Frame默认的布局管理器

     GridLayout(网格布局管理器)

      *规则的矩阵

     CardLayout(卡片布局管理器)

      *选项卡

     GridBagLayout(网格包1布局管理器)

      *非规则的矩阵

    窗体监听

    public class demo1_Frame {
    
        public static void main(String[] args) {
            Frame f1 = new Frame("QQ");
            f1.setSize(400,600);//大小
            f1.setLocation(600, 50);//位置
            f1.setIconImage(Toolkit.getDefaultToolkit().createImage("dog.jpg"));//图标
            Button b1=new Button("按钮1");
            
            f1.add(b1);
            f1.setLayout(new BorderLayout());
    //        f1.addWindowListener(new MyWindowListener());
            f1.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            f1.setVisible(true);//窗口可见
            
        }
    
    }
    /*class MyaddWindowListener implements WindowListener{
    
        public void windowActivated(WindowEvent e) {
        
            
        }
    
        public void windowClosed(WindowEvent e) {
            System.out.println("Closed");
            
        }
    
        public void windowClosing(WindowEvent e) {
            System.exit(0);
            
        }
    
        public void windowDeactivated(WindowEvent e) {
            
            
        }
    
        @Override
        public void windowDeiconified(WindowEvent e) {
            
            
        }
    
        @Override
        public void windowIconified(WindowEvent e) {
            
            
        }
    
        @Override
        public void windowOpened(WindowEvent e) {
        
            
        }}*/
    //class MyWindowListener extends WindowAdapter{
    //    public void windowClosing(WindowEvent e) {
    //        System.exit(0);
    //    };
    //}
    案例

    键盘监听

    b1.addKeyListener(new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                        System.exit(0);
                    }
                }
            });
    案例

    适配器

      在使用监听器的时候,需要定义一个类事件监听器接口

      通常接口中有多个方法,而程序中不一定所有的都用到,但又必须重写,这很繁琐

      适配器简化了这些操作,我们定义监听器时只要继承适配器,然后重写需要的方法即可

    适配器原理

      适配器就是一个类,实现了监听器接口,所有抽象方法都重写了,但是方法全是空的

      适配器类需要定义成抽象类的,因为创建该类对象,调用空方法就可以了

    GUI事件处理

      事件:用户的一个操作

      事件源:被操作的组件

      监听器:一个自定义类的对象,实现了监听器接口。包含时间处理犯法,把监听器添加在时间源上,当事件发生的时候虚拟机就会自动调用监听器中的事件处理方法

      

  • 相关阅读:
    HTML 基础 元素 标签
    HTML5 元素介绍
    网站程序 模板下载 下载 ftp
    域名解析和空间绑定
    如何选择云虚拟主机操作系统?
    网站备案查询
    响应式网站01
    项目中使用百度统计和友盟统计
    项目中使用http referer,为了盗取图片资源
    vue-awesome-swiper中的数据异步加载
  • 原文地址:https://www.cnblogs.com/JungTan0113/p/10973995.html
Copyright © 2011-2022 走看看