热门课程

免费试听

上课方式

开班时间

当前位置: 首页 -   文章 -   新闻动态 -   正文

分享Thread 中用到的两种设计模式

知了堂姐
2024-07-08 17:22:16
0

  其实有时候不能简单说哪种设计用到了哪些设计模式,设计模式本身就是对很多代码设计经验的总结。


  模板模式
  模板模式的应用就比较好理解了。在创建线程一般使用构建 Thread 类或者实现 Runnable 接口(这种说法是错误的,最起码是不严谨的,在 JDK 中代表线程的就只有 Thread 这个类,线程的执行单元就是 run() 方法,你可以通过继承 Thread 然后重写 run() 方法实现自己的业务逻辑,也可以实现 Runnable 接口实现自己的业务逻辑),启动线程是使用的 start() 方法,但是具体业务逻辑还是在 run() 方法中。


/**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the run method of this thread.
     * 

* The result is that two threads are running concurrently: the * current thread (which returns from the call to the * start method) and the other thread (which executes its * run method). *

* It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. * * @exception IllegalThreadStateException if the thread was already * started. * @see #run() * @see #stop() */ public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } }


分享Thread 中用到的两种设计模式

  这样可以将业务逻辑和线程的逻辑分离。在模板设计模式在Thread的应用中看到了一个挺好的例子:
 
/**
 * Description
 * 

*

* DATE 2018/10/26. * * @author caichengzhang. */ public class Template { public Template() { } public final void start(){ System.out.println("stat方法启动!"); run(); System.out.println("start方法结束!"); } public void run(){} public static void main(String[] args) { Template template = new Template(){ @Override public void run() { System.out.println("run方法开始运行!"); } }; template.start(); } }

  策略模式
  结合上面的 Thread 的 start() 方法,注释说明 start() 方法执行的是它的 run() 方法,再看看 Thread 的 run() 方法,如果构造传入 Runnable,就执行 Runnable 的 run() 方法,否则就需要重写 Thread 的 run() 方法。
/**
     * If this thread was constructed using a separate
     * Runnable run object, then that
     * Runnable object's run method is called;
     * otherwise, this method does nothing and returns.
     * 

* Subclasses of Thread should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ @Override public void run() { if (target != null) { target.run(); } }

  /* What will be run. */
    private Runnable target;

  无论是 Runnable 的 run() 方法,还是 Thread 类本身的 run() 方法(事实上 Thread 类也是实现了 Runnable 接口)都是想将线程的控制本身和业务逻辑的运行分离开来,达到职责分明、功能单一的原则,这一点与 GoF 设计模式中的策略设计模式很相似。
  这个 Runnable 就是策略接口,针对不同的策略实现,执行相应的方法。这样对策略进行不同的实现即可。
package com.example.threaddesign;
 
/**
 * @author Dongguabai
 * @date 2018/12/2 20:58
 */
public class ThreadTest {
 
    public static void main(String[] args) {
        Thread thread = new Thread(new Strategy1(), "执行者");
        thread.start();
    }
 
    static class Strategy1 implements Runnable {
 
        @Override
        public void run() {
            System.out.println("策略一");
        }
    }
 
    static class Strategy3 implements Runnable {
 
        @Override
        public void run() {
            System.out.println("策略三");
        }
    }
 
    static class Strategy2 implements Runnable {
 
        @Override
        public void run() {
            System.out.println("策略二");
        }
    }
}

    版权声明:本文来源于网络,由知了堂搜集整理。

    知了堂为大学生/初学者提供编程实践学习指导和服务,通过前沿项目实战、自有学习/实践平台、专业学习体系、形式多样的线上线下活动,让学习者真正掌握编程技能、具备编程实战经验,获得入职/职场晋升能力,同时知了堂着力打造一个有温度的学习社区,通过链接学习导师、举行社区活动、规范社区交流机制,为学习者提供交流、分享、项目组队等空间,共建最有价值的编程学习者成长社区。 


大家都在看

知了堂官网V3第一版内测邀请

2024-07-08 浏览次数:0

零经验可以做软件测试吗?能找到工作吗?

2024-07-08 浏览次数:0

网络安全培训机构哪个好些,怎么挑选网络安全培训机...

2024-07-08 浏览次数:0

计算机毕设选题怎么做?收藏好这份攻略!

2024-07-08 浏览次数:0

html5与css常规面试技术题库

2024-07-08 浏览次数:0

什么是静态测试?静态测试工具有哪些?

2024-07-08 浏览次数:0
最新资讯