java多线程的使用与原理

【Java】Java多线程神器:join使用及原理 1.概述 转载:http://www.javastack.cn/article/2017/java-thread-join/ join() join()是线程类Thread的方法,官方的说明是: Waits for this thread to die. 等待这个线程结束,也就是说当前线程等待这个线程结束后再继续执行,下面来看这个示例就明白了。 示例 public static void main(String[] args) throws Exception { System.out.println. 阅读详情

1、线程池简介:
    多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。    
    假设一个服务器完成一项任务所需时间为:T1 创建线程时间,T2 在线程中执行任务的时间,T3 销毁线程时间。

    如果:T1 + T3 远大于 T2,则可以采用线程池,以提高服务器性能。
                一个线程池包括以下四个基本组成部分:
                1、线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
                2、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
                3、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
                4、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。
                
    线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了。
    线程池不仅调整T1,T3产生的时间段,而且它还显著减少了创建线程的数目,看一个例子:
    假设一个服务器一天要处理50000个请求,并且每个请求需要一个单独的线程完成。在线程池中,线程数一般是固定的,所以产生线程总数不会超过线程池中线程的数目,而如果服务器不利用线程池来处理这些请求则线程总数为50000。一般线程池大小是远小于50000。所以利用线程池的服务器程序不会为了创建50000而在处理请求时浪费时间,从而提高效率。

    代码实现中并没有实现任务接口,而是把Runnable对象加入到线程池管理器(ThreadPool),然后剩下的事情就由线程池管理器(ThreadPool)来完成了

 

[java]  view plain  copy
  1. package mine.util.thread;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.List;  
  5.   
  6. /** 
  7.  * 线程池类,线程管理器:创建线程,执行任务,销毁线程,获取线程基本信息 
  8.  */  
  9. public final class ThreadPool {  
  10.     // 线程池中默认线程的个数为5  
  11.     private static int worker_num = 5;  
  12.     // 工作线程  
  13.     private WorkThread[] workThrads;  
  14.     // 未处理的任务  
  15.     private static volatile int finished_task = 0;  
  16.     // 任务队列,作为一个缓冲,List线程不安全  
  17.     private List<Runnable> taskQueue = new LinkedList<Runnable>();  
  18.     private static ThreadPool threadPool;  
  19.   
  20.     // 创建具有默认线程个数的线程池  
  21.     private ThreadPool() {  
  22.         this(5);  
  23.     }  
  24.   
  25.     // 创建线程池,worker_num为线程池中工作线程的个数  
  26.     private ThreadPool(int worker_num) {  
  27.         ThreadPool.worker_num = worker_num;  
  28.         workThrads = new WorkThread[worker_num];  
  29.         for (int i = 0; i < worker_num; i++) {  
  30.             workThrads[i] = new WorkThread();  
  31.             workThrads[i].start();// 开启线程池中的线程  
  32.         }  
  33.     }  
  34.   
  35.     // 单态模式,获得一个默认线程个数的线程池  
  36.     public static ThreadPool getThreadPool() {  
  37.         return getThreadPool(ThreadPool.worker_num);  
  38.     }  
  39.   
  40.     // 单态模式,获得一个指定线程个数的线程池,worker_num(>0)为线程池中工作线程的个数  
  41.     // worker_num<=0创建默认的工作线程个数  
  42.     public static ThreadPool getThreadPool(int worker_num1) {  
  43.         if (worker_num1 <= 0)  
  44.             worker_num1 = ThreadPool.worker_num;  
  45.         if (threadPool == null)  
  46.             threadPool = new ThreadPool(worker_num1);  
  47.         return threadPool;  
  48.     }  
  49.   
  50.     // 执行任务,其实只是把任务加入任务队列,什么时候执行有线程池管理器觉定  
  51.     public void execute(Runnable task) {  
  52.         synchronized (taskQueue) {  
  53.             taskQueue.add(task);  
  54.             taskQueue.notify();  
  55.         }  
  56.     }  
  57.   
  58.     // 批量执行任务,其实只是把任务加入任务队列,什么时候执行有线程池管理器觉定  
  59.     public void execute(Runnable[] task) {  
  60.         synchronized (taskQueue) {  
  61.             for (Runnable t : task)  
  62.                 taskQueue.add(t);  
  63.             taskQueue.notify();  
  64.         }  
  65.     }  
  66.   
  67.     // 批量执行任务,其实只是把任务加入任务队列,什么时候执行有线程池管理器觉定  
  68.     public void execute(List<Runnable> task) {  
  69.         synchronized (taskQueue) {  
  70.             for (Runnable t : task)  
  71.                 taskQueue.add(t);  
  72.             taskQueue.notify();  
  73.         }  
  74.     }  
  75.   
  76.     // 销毁线程池,该方法保证在所有任务都完成的情况下才销毁所有线程,否则等待任务完成才销毁  
  77.     public void destroy() {  
  78.         while (!taskQueue.isEmpty()) {// 如果还有任务没执行完成,就先睡会吧  
  79.             try {  
  80.                 Thread.sleep(10);  
  81.             } catch (InterruptedException e) {  
  82.                 e.printStackTrace();  
  83.             }  
  84.         }  
  85.         // 工作线程停止工作,且置为null  
  86.         for (int i = 0; i < worker_num; i++) {  
  87.             workThrads[i].stopWorker();  
  88.             workThrads[i] = null;  
  89.         }  
  90.         threadPool=null;  
  91.         taskQueue.clear();// 清空任务队列  
  92.     }  
  93.   
  94.     // 返回工作线程的个数  
  95.     public int getWorkThreadNumber() {  
  96.         return worker_num;  
  97.     }  
  98.   
  99.     // 返回已完成任务的个数,这里的已完成是只出了任务队列的任务个数,可能该任务并没有实际执行完成  
  100.     public int getFinishedTasknumber() {  
  101.         return finished_task;  
  102.     }  
  103.   
  104.     // 返回任务队列的长度,即还没处理的任务个数  
  105.     public int getWaitTasknumber() {  
  106.         return taskQueue.size();  
  107.     }  
  108.   
  109.     // 覆盖toString方法,返回线程池信息:工作线程个数和已完成任务个数  
  110.     @Override  
  111.     public String toString() {  
  112.         return "WorkThread number:" + worker_num + "  finished task number:"  
  113.                 + finished_task + "  wait task number:" + getWaitTasknumber();  
  114.     }  
  115.   
  116.     /** 
  117.      * 内部类,工作线程 
  118.      */  
  119.     private class WorkThread extends Thread {  
  120.         // 该工作线程是否有效,用于结束该工作线程  
  121.         private boolean isRunning = true;  
  122.   
  123.         /* 
  124.          * 关键所在啊,如果任务队列不空,则取出任务执行,若任务队列空,则等待 
  125.          */  
  126.         @Override  
  127.         public void run() {  
  128.             Runnable r = null;  
  129.             while (isRunning) {// 注意,若线程无效则自然结束run方法,该线程就没用了  
  130.                 synchronized (taskQueue) {  
  131.                     while (isRunning && taskQueue.isEmpty()) {// 队列为空  
  132.                         try {  
  133.                             taskQueue.wait(20);  
  134.                         } catch (InterruptedException e) {  
  135.                             e.printStackTrace();  
  136.                         }  
  137.                     }  
  138.                     if (!taskQueue.isEmpty())  
  139.                         r = taskQueue.remove(0);// 取出任务  
  140.                 }  
  141.                 if (r != null) {  
  142.                     r.run();// 执行任务  
  143.                 }  
  144.                 finished_task++;  
  145.                 r = null;  
  146.             }  
  147.         }  
  148.   
  149.         // 停止工作,让该线程自然执行完run方法,自然结束  
  150.         public void stopWorker() {  
  151.             isRunning = false;  
  152.         }  
  153.     }  
  154. }  

 

测试代码:

[java]  view plain  copy
  1. package mine.util.thread;  
  2.   
  3. //测试线程池  
  4. public class TestThreadPool {  
  5.     public static void main(String[] args) {  
  6.         // 创建3个线程的线程池  
  7.         ThreadPool t = ThreadPool.getThreadPool(3);  
  8.         t.execute(new Runnable[] { new Task(), new Task(), new Task() });  
  9.         t.execute(new Runnable[] { new Task(), new Task(), new Task() });  
  10.         System.out.println(t);  
  11.         t.destroy();// 所有线程都执行完成才destory  
  12.         System.out.println(t);  
  13.     }  
  14.   
  15.     // 任务类  
  16.     static class Task implements Runnable {  
  17.         private static volatile int i = 1;  
  18.   
  19.         @Override  
  20.         public void run() {// 执行任务  
  21.             System.out.println("任务 " + (i++) + " 完成");  
  22.         }  
  23.     }  
  24. }  


 

运行结果:

WorkThread number:3  finished task number:0  wait task number:6
任务 1 完成
任务 2 完成
任务 3 完成
任务 4 完成
任务 5 完成
任务 6 完成
WorkThread number:3  finished task number:6  wait task number:0

分析:由于并没有任务接口,传入的可以是自定义的任何任务,所以线程池并不能准确的判断该任务是否真正的已经完成(真正完成该任务是这个任务的run方法执行完毕),只能知道该任务已经出了任务队列,正在执行或者已经完成。

2、Java类库中提供的线程池简介:

     java提供的线程池更加强大,相信理解线程池的工作原理,看类库中的线程池就不会感到陌生了。

Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

 

(1) newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  5.  public static void main(String[] args) {  
  6.   ExecutorService cachedThreadPool = Executors.newCachedThreadPool();  
  7.   for (int i = 0; i < 10; i++) {  
  8.    final int index = i;  
  9.    try {  
  10.     Thread.sleep(index * 1000);  
  11.    } catch (InterruptedException e) {  
  12.     e.printStackTrace();  
  13.    }  
  14.    cachedThreadPool.execute(new Runnable() {  
  15.     public void run() {  
  16.      System.out.println(index);  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  

 

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
 
(2) newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  5.  public static void main(String[] args) {  
  6.   ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);  
  7.   for (int i = 0; i < 10; i++) {  
  8.    final int index = i;  
  9.    fixedThreadPool.execute(new Runnable() {  
  10.     public void run() {  
  11.      try {  
  12.       System.out.println(index);  
  13.       Thread.sleep(2000);  
  14.      } catch (InterruptedException e) {  
  15.       e.printStackTrace();  
  16.      }  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  

 
因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

 

(3)  newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.Executors;  
  3. import java.util.concurrent.ScheduledExecutorService;  
  4. import java.util.concurrent.TimeUnit;  
  5. public class ThreadPoolExecutorTest {  
  6.  public static void main(String[] args) {  
  7.   ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
  8.   scheduledThreadPool.schedule(new Runnable() {  
  9.    public void run() {  
  10.     System.out.println("delay 3 seconds");  
  11.    }  
  12.   }, 3, TimeUnit.SECONDS);  
  13.  }  
  14. }  

 
表示延迟3秒执行。

定期执行示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.Executors;  
  3. import java.util.concurrent.ScheduledExecutorService;  
  4. import java.util.concurrent.TimeUnit;  
  5. public class ThreadPoolExecutorTest {  
  6.  public static void main(String[] args) {  
  7.   ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
  8.   scheduledThreadPool.scheduleAtFixedRate(new Runnable() {  
  9.    public void run() {  
  10.     System.out.println("delay 1 seconds, and excute every 3 seconds");  
  11.    }  
  12.   }, 1, 3, TimeUnit.SECONDS);  
  13.  }  
  14. }  

 
表示延迟1秒后每3秒执行一次。

 

(4) newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  5.  public static void main(String[] args) {  
  6.   ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  
  7.   for (int i = 0; i < 10; i++) {  
  8.    final int index = i;  
  9.    singleThreadExecutor.execute(new Runnable() {  
  10.     public void run() {  
  11.      try {  
  12.       System.out.println(index);  
  13.       Thread.sleep(2000);  
  14.      } catch (InterruptedException e) {  
  15.       e.printStackTrace();  
  16.      }  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  

 
结果依次输出,相当于顺序执行各个任务。

你可以使用JDK自带的监控工具来监控我们创建的线程数量,运行一个不终止的线程,创建指定量的线程,来观察:
工具目录:C:\Program Files\Java\jdk1.6.0_06\bin\jconsole.exe
运行程序做稍微修改:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  5.  public static void main(String[] args) {  
  6.   ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();  
  7.   for (int i = 0; i < 100; i++) {  
  8.    final int index = i;  
  9.    singleThreadExecutor.execute(new Runnable() {  
  10.     public void run() {  
  11.      try {  
  12.       while(true) {  
  13.        System.out.println(index);  
  14.        Thread.sleep(10 * 1000);  
  15.       }  
  16.      } catch (InterruptedException e) {  
  17.       e.printStackTrace();  
  18.      }  
  19.     }  
  20.    });  
  21.    try {  
  22.     Thread.sleep(500);  
  23.    } catch (InterruptedException e) {  
  24.     e.printStackTrace();  
  25.    }  
  26.   }  
  27.  }  
  28. }  


13 万字 C 语言从入门到精通保姆级教程2021 年版 13 万字C语言保姆级教程,从入门到精通。 阅读详情

相关推荐

Uniapp-APP后台保活插件(安卓后台保活)

Uniapp-APP后台保活插件(安卓后台保活)亲测有效!

weixin_57844432的博客 1万+

java多线程原理_Java中多线程原理详解

Java是少数的集中支持多线程的语言之一,大多数的语言智能运行单独的一个程序块,无法同时运行不同的多个程序块,Java的多线程机制弥补了这个缺憾,它可以让不同的程序块一起运行,这样可以让程序运行更加顺畅,同时也达到了多任务处理的目的。一、线程和进程的概念现在的操作系统是多任务操作系统。多线程是实现多任务的一种方式。进程是程序的一个动态执行过程,是指一个内存中运行的应用程序,每个进程都有自己独立的一...

weixin_33241808的博客 1095

MATLAB2021b详细安装教程

1.下载 2.安装 下载安装包后打开iso文件,若是无法打开请用解压软件打开。 ①打开MATLAB_R2021b_win64,双击软件开始安装 ② 一直点击下一步,直到步骤③ ③选择我已有我的许可证的文件密钥,并输入62551-02011-26857-57509-64399-54230-13279-37181-62117-65158-40352-64197-45508-24369-45954-39446-39538-16936-10698-58393-44718-32560-10501-40

惜洛-Jankin的博客 9万+

Java 多线程原理详解

线程是操作系统能够进行调度的最小单元,是一个程序的执行路径。一个进程可以包含多个线程,每个线程执行不同的任务,但它们共享相同的内存空间和资源。这使得线程之间的通信和协作更加高效,但也引发了线程同步和竞争条件等问题。Java 多线程编程是一门复杂的技术,理解其原理并掌握各种同步机制和并发工具类是编写高效多线程程序的关键。通过合理设计线程模型、正确使用同步工具,并遵循多线程编程的最佳实践,可以有效提高程序的性能和可靠性。同时,避免常见的并发问题(如死锁、线程饥饿)也是确保多线程程序稳定运行的重要方面。

lssffy的博客 895

开关变换器分析:大信号模型与小信号模型

是电力电子系统建模中的两类基本方法,分别用于描述系统在不同工作条件下的动态行为。它们的核心区别在于是否对变量进行线性化近似,以及适用的分析场景。

创新改变世界! 1909

Spring AI Alibaba Graph进阶:如何用图算法优化你的推荐系统?

本文深入探讨了如何利用Spring AI Alibaba Graph的图算法优化推荐系统。通过分析用户行为数据的网络化特征,结合加权随机游走和社区发现算法,显著提升推荐精准度和用户点击率。文章还分享了混合推荐架构设计、性能优化技巧及生产环境中的实战经验,为开发者提供了一套完整的图算法推荐解决方案。

weixin_33738555的博客 128

一篇搞懂Java多线程(全网最细)

Java多线程是一种强大而有趣的编程概念。它允许程序同时执行多个任务,就像一个宏大的交响乐团。每个线程都是一个独立的执行路径,有自己的速度和优先级。那么,我们期待多线程能给我们带来什么呢?

让优秀成为一种习惯! 1万+

Codesys 3.5报警功能配置保姆级教程:从变量定义到确认方式(含REF/ACK详解)

本文详细介绍了Codesys 3.5报警功能的配置流程,从变量定义到确认方式的选择,特别解析了REF和ACK两种确认方式的底层逻辑。通过实战案例和代码示例,帮助工程师快速掌握报警系统的搭建与调试技巧,提升工业自动化项目的可靠性。

weixin_29245767的博客 458

JAVA多线程基本原理

JAVA多线程 1. 什么是线程?线程和进程的区别? 进程:进程是指处于运行过程中的程序,并且具有一定的独立功能。进程是系统进行资源分配和调度的一个单位。当一个程序进入内存运行时,就成为一个进程。 线程:线程是进程的组成部分,一个进程可以拥有多个线程,而一个线程必须拥有一个父进程。线程可以拥有自己的堆栈,自己的程序计数器和自己的局部变量,但不能拥有系统资源。它与父进程的其他线程共享该进程的所有资源。 主线程:在Java中必然有一个执行路径(线程)从main方法开始的,一直执行到main方法结束。

m0_58355200的博客 2084

集成calibre到cadence virtuoso环境中 load: can‘t access file - “/opt/eda/Mentor/lib/calibre.skl“

项目场景: 设想是将Calibre集成到cadence virtuoso中,但网上的解决办法尝试过在本机上实验都有点问题,因此想记录下来我的解决办法仅供参考。 问题描述: 安装好cadence, calibre之后打开virtuoso,CIW窗口显示 *Error* load: can't access file - "/opt/eda/Mentor/lib/calibre.skl" 问题是出在calibre.skl的加载路径出错,尝试网上的在工程目录下修改.cdsinit文件,添加calibre安装

weixin_52714276的博客 1万+

U盘安装单系统ubuntu10.04之全过程&拔掉U盘后系统无法启动

借助U盘把电脑装成ubuntu单系统之过程记录,以及遇到拔掉U盘后系统无法启动问题,电脑就显示: Non-System disk or disk error, replace and strike any key when ready

CXHPLY的专栏 8680

Java多线程及原理

java线程池及原理

javaDB_EAD的专栏 539

问答式AI vs 智能体(Agent):它们有什么不同?

你肯定用过 ChatGPT 或文心一言——问它一个问题,它给你一个答案。AI Agent(AI智能体)。很多人搞不清楚:它们不都是"AI"吗?有什么区别?这篇文章用一个最简单的类比,彻底讲清楚这两者的本质差异。框架特点适合人群AutoGPT完全自主执行任务,链式思考开发者MetaGPT模拟团队协作,多角色分工开发者LangChain最流行的Agent开发框架开发者Dify可视化无代码搭建Agent非技术用户Coze(扣子)字节跳动出品,国内最易用普通用户WorkBuddy。

Johnny2004的专栏 447

Java中多线程的使用(超级超级详细)+多线程的实现原理 2

Java中多线程的使用(超级超级详细)+多线程的实现原理+线程的创建方式+同步代码块 1.多线程的实现原理 先上代码,通过代码加图的方式来解说 public class Main { public static void main(String[] args) { MyThread myThread = new MyThread("one"); myThread.start(); int i=20; for (int i1 = i; i

pjh88的博客 202

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

(Java多线程)多线程原理和使用

并发与并行 并发:指两个或多个事件在同一个时间段内发生。 并行:指两个或多个事件在同一时刻发生(同时发生)。 在操作系统中,安装了多个程序,并发指的是在一段时间内宏观上有多个程序同时运行,这在单 CPU 系统中,每一时刻只能有一道程序执行,即微观上这些程序是分时的交替运行,只不过是给人的感觉是同时运行,那是因为分时交替运行的时间是非常短的。 而在多个 CPU 系统中,则这些可以并发执行的程序便可以分配到多个处理器上(CPU),实现多任务并行执行,即利用每个处理器来处理一个可以并发执行的程序,这样多个程

我真的很不错的博客 550

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

JAVA线程及多线程原理及使用

JAVA线程及多线程学习JAVA线程什么是线程线程的状态JAVA线程的实现方式为什么需要多线程线程池的作用及原理JAVA JDK提供的线程池工具类 JAVA线程 什么是线程 线程是一条代码执行流程,完成一组代码的执行. 这一组代码,我们往往称为一个任务. java Thread:线程 Runnable:任务 代码有CPU执行 (code)任务(Runnable)-...

weixin_39172079的博客 407

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Java多线程9:ThreadLocal原理和使用场景

前言:面试官经常会问到 ThreadLocal 是什么?他其实想考察候选人对ThreadLocal的定义、原理和应用场景的了解程度。 一、ThreadLocal定义 ThreadLocal,线程本地变量,顾名思义,它是每个线程私有的本地变量。通俗点讲,当你创建了一个ThreadLocal变量,每个线程在访问该变量时,都会拷贝一个副本至本地内存,所以多线程下操作ThreadLocal变量时,其实各自都是在操作自己拷贝的副本,互不影响,这样自然而然就避免了线程安全问题。 ThreadLocal有点类似

何哥的博客 4499

JAVA基础面试题:多线程编程中的线程池原理与使用场景

线程池是多线程编程中非常重要的一个组件,合理使用线程池可以显著提升系统性能。我会尽量用简单的语言来解释,希望能让你听得明白。听说你在大厂有十年的Java后端开发经验,能否分享一下线程池的原理和使用场景?线程池是一种管理线程的机制,它通过预先创建一组线程并维护这些线程的生命周期,避免了频繁创建和销毁线程的开销。Victor:线程池是多线程编程中的利器,合理使用可以显著提升系统性能和稳定性。希望我的回答能帮助你理解线程池的核心原理和使用场景。简单来说,线程池就像是一个“线程工厂”,负责高效地管理和调度线程。

Victor_119的博客 504

1.6w字图解Java并发:多线程挑战、线程状态和通信、死锁AQS、ReentrantLock、Condition 使用和原理

ObjectMonitor 中有两个队列,_WaitSet 和 _EntryList,用来保存 ObjectWaiter 对象列表( 每个等待锁的线程都会被封装成 ObjectWaiter 对象),_owner 指向持有 ObjectMonitor 对象的线程,当多个线程同时访问一段同步代码时,首先会进入 _EntryList 集合,当线程获取到对象的 monitor 后进入 _Owner 区域并把 monitor 中的 owner 变量设置为当前线程同时 monitor 中的计数器 count 加 1。

码哥字节 862

Java多线程原理及使用探讨

摘要: Java并发编程:线程池的使用   在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题:   如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。Java并发编程:线程池的使用  在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但

xiangbole的博客 2160

java手机下载功能实现原理,Android学习札记-java实现多线程下载器,30_多线程下载原理介绍和使用...

Android学习笔记---java实现多线程下载器,30_多线程下载原理介绍和使用2013-04-0130_多线程下载原理--------------------a.文件下载原里:使用http协议实现多线程下载b.采用多线程下载,可以抢占服务器cpu的处理时间,实现快速下载c.使用多线程下载文件可以更快完成文件的下载,多线程下载文件之所以快,是因为其抢占的服务器资源多。如:假设服务器同时最多服务...

weixin_39891158的博客 526

java多线程模式ThreadLocal原理简述及其使用详解

java多线程模式ThreadLocal原理简述及其使用详解 源代码下载地址:http://www.zuidaima.com/share/1781557457128448.htm

云淡风轻、仅此一抹 798

java thread 多线程_Java多线程原理及Thread类的使用

一、进程与线程的区别1.进程是应用程序在内存总分配的空间。(正在运行中的程序)2.线程是进程中负责程序执行的执行单元、执行路径。3.一个进程中至少有一个线程在负责进程的运行。4.一个进程中有多个线程在运行的程序,为多线程程序。5.多线程技术是为了解决多部分代码同时执行。6.多线程的优点是合理的使用资源。二、jvm中的多线程1.jvm中的多线程有很多,其中有负责定义代码运行的线程(这个从main方法...

weixin_35831969的博客 188

Java 多线程编程详解:原理、使用、应用场景、优缺点与实践指南

根据Oracle官方文档(截至2025年),Java的多线程支持源于JDK 1.0时代,并不断演进,到JDK 21(当前最新长期支持版)中,引入了虚拟线程(Virtual Threads)和结构化并发(Structured Concurrency),进一步简化了并发编程。线程(Thread)是进程内的执行单元,共享进程资源,但有独立的栈和程序计数器。接下来,我们深入原理。从JDK 19起,引入虚拟线程(Project Loom),它们是用户级线程,轻量(数百万个可创建),不绑定OS线程,适合IO密集任务。

lssffy的博客 666

Java线程详解及多线程线程池使用与原理

了解线程池必看课程

pgcdnameming的博客 559

深入java多线程,深入理解volatile使用与原理

1、认识volatile volatile是用来修饰变量的。与synchronized不同,synchronized是用来修饰方法和代码块。volatile称之为轻量级锁,被volatile修改的变量在各个线程之间是可见的,保持线程之间的可见性,可见性是指多个线程共享同一个变量,当一个线程修改了这个变量,另外的线程能感知到这个变量的变化并进行读取。 2、volatile实现原理 ...

a281246240的专栏 278
上一篇: Mybatis配置分布式缓存
下一篇: Mybatis分布式事物
CookSjg
博客等级 码龄10年 1粉丝 12原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值