多线程基础(十):LockSupport源码及其使用

【Java开发日记】我们来说说 LockSupport 的 park 和 unpark LockSupport 和 CAS 是Java并发包中很多并发工具控制机制的基础,它们底层其实都是依赖Unsafe实现。很多锁的类都是基于LockSupport的park和unpark来实现的,所以了解LockSupport类是非常重要的。如果小假的内容对你有帮助,请评论。创作不易,大家的支持就是我坚持下去的动力! 阅读详情


在前面学习过java线程间通信的几种方式,分别是synchronized结合wait/notify。以及ReentrantLock结合Condation的await和signal方法。那么实际上还有一种方法也能实现线程通信,那就是LockSupport。我们来看看其源码。

1.类注释说明

在类源码中有大段注释,在前面学习的过程中不难发现,凡是java代码中的注释,都是非常重要的。

/**
 * Basic thread blocking primitives for creating locks and other
 * synchronization classes.
 *
 * <p>This class associates, with each thread that uses it, a permit
 * (in the sense of the {@link java.util.concurrent.Semaphore
 * Semaphore} class). A call to {@code park} will return immediately
 * if the permit is available, consuming it in the process; otherwise
 * it <em>may</em> block.  A call to {@code unpark} makes the permit
 * available, if it was not already available. (Unlike with Semaphores
 * though, permits do not accumulate. There is at most one.)
 *
 * <p>Methods {@code park} and {@code unpark} provide efficient
 * means of blocking and unblocking threads that do not encounter the
 * problems that cause the deprecated methods {@code Thread.suspend}
 * and {@code Thread.resume} to be unusable for such purposes: Races
 * between one thread invoking {@code park} and another thread trying
 * to {@code unpark} it will preserve liveness, due to the
 * permit. Additionally, {@code park} will return if the caller's
 * thread was interrupted, and timeout versions are supported. The
 * {@code park} method may also return at any other time, for "no
 * reason", so in general must be invoked within a loop that rechecks
 * conditions upon return. In this sense {@code park} serves as an
 * optimization of a "busy wait" that does not waste as much time
 * spinning, but must be paired with an {@code unpark} to be
 * effective.
 *
 * <p>The three forms of {@code park} each also support a
 * {@code blocker} object parameter. This object is recorded while
 * the thread is blocked to permit monitoring and diagnostic tools to
 * identify the reasons that threads are blocked. (Such tools may
 * access blockers using method {@link #getBlocker(Thread)}.)
 * The use of these forms rather than the original forms without this
 * parameter is strongly encouraged. The normal argument to supply as
 * a {@code blocker} within a lock implementation is {@code this}.
 *
 * <p>These methods are designed to be used as tools for creating
 * higher-level synchronization utilities, and are not in themselves
 * useful for most concurrency control applications.  The {@code park}
 * method is designed for use only in constructions of the form:
 *
 *  <pre> {@code
 * while (!canProceed()) { ... LockSupport.park(this); }}</pre>
 *
 * where neither {@code canProceed} nor any other actions prior to the
 * call to {@code park} entail locking or blocking.  Because only one
 * permit is associated with each thread, any intermediary uses of
 * {@code park} could interfere with its intended effects.
 *
 * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out
 * non-reentrant lock class:
 *  <pre> {@code
 * class FIFOMutex {
 *   private final AtomicBoolean locked = new AtomicBoolean(false);
 *   private final Queue<Thread> waiters
 *     = new ConcurrentLinkedQueue<Thread>();
 *
 *   public void lock() {
 *     boolean wasInterrupted = false;
 *     Thread current = Thread.currentThread();
 *     waiters.add(current);
 *
 *     // Block while not first in queue or cannot acquire lock
 *     while (waiters.peek() != current ||
 *            !locked.compareAndSet(false, true)) {
 *       LockSupport.park(this);
 *       if (Thread.interrupted()) // ignore interrupts while waiting
 *         wasInterrupted = true;
 *     }
 *
 *     waiters.remove();
 *     if (wasInterrupted)          // reassert interrupt status on exit
 *       current.interrupt();
 *   }
 *
 *   public void unlock() {
 *     locked.set(false);
 *     LockSupport.unpark(waiters.peek());
 *   }
 * }}</pre>
  */

上面的注释的大意为:
LockSupport是一个创建锁和其他同步类的线程阻塞原语。
在个类在使用其的每个线程上关联一个许可类( java.util.concurrent.Semaphore)。如果许可证可用,对park调用将立即返回,并在进程中使用它,否则就会阻塞。当许可证不可用的情况下调用unpark方法则可以使许可证可用。与信号量Semaphore不同的是,许可证不会累计,最多只有一个。
方法park和unpark提供了有效的阻塞和解除阻塞线程的功能。但是不能与已废弃的方法suspend和resume方法一样,用于如下目的:在一个调用park的线程和另外一个调用unpark的线程之间对许可证进行竞争,保持活力。另外,park在调用方线程被中断的时候返回。并且支持超时。park方法也可能在任何其他的时候返回,因为没有原因,因此通常必须在返回时重新检查条件中循环调用。从这个意义上说,park是繁忙等待的优化。它不会浪费太多的时间自旋,但是必须与unpark配合使用才有效。
park有三种调用形式,每种都支持blocker对象参数,此对象在线程被阻塞的时候被记录,以便监视和诊断工具能够识别线程被阻塞的原因。这类工具可以用getBlocker的方式访问被阻塞队程序,强烈建议使用带有bloker参数的方法,而不是不带这些参数的原始方法。在锁实现中做为blocker提供的常规参数是this。
这些方法被设计用来做为创建更高级别的同步工具。而不是自己在对大多数并发控制程英语程序中使用,park方法仅仅用于下列形式的构造:

while (!canProceed()) { 
... 
LockSupport.park(this); 
    
}}

在canProcess方法或者任何其他操作之前调用park需要加锁或者阻塞,因为只有一个许可证,这是与每个线程都关联的,任何中间方使用park都可能对park的预期效果造成影响。
如下,这是一个先进先出的不可重入的锁的伪代码:

 class FIFOMutex {
   private final AtomicBoolean locked = new AtomicBoolean(false);
   private final Queue<Thread> waiters
     = new ConcurrentLinkedQueue<Thread>();

   public void lock() {
     boolean wasInterrupted = false;
     Thread current = Thread.currentThread();
     waiters.add(current);

    // Block while not first in queue or cannot acquire lock
     while (waiters.peek() != current ||
            !locked.compareAndSet(false, true)) {
      LockSupport.park(this);
       if (Thread.interrupted()) // ignore interrupts while waiting
        wasInterrupted = true;
     }

     waiters.remove();
     if (wasInterrupted)          // reassert interrupt status on exit
       current.interrupt();
   }

   public void unlock() {
     locked.set(false);
     LockSupport.unpark(waiters.peek());
   }

2.主要方法

2.1 park

park我们可以形象的理解为泊车的意思,实际上,park就是一个标识0-1的信号的共享变量。如果park,则标识占用。那么信号就变成0.如果执行unpark则信号变成1。

/**
 * Disables the current thread for thread scheduling purposes unless the
 * permit is available.
 *
 * <p>If the permit is available then it is consumed and the call
 * returns immediately; otherwise the current thread becomes disabled
 * for thread scheduling purposes and lies dormant until one of three
 * things happens:
 *
 * <ul>
 *
 * <li>Some other thread invokes {@link #unpark unpark} with the
 * current thread as the target; or
 *
 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 * the current thread; or
 *
 * <li>The call spuriously (that is, for no reason) returns.
 * </ul>
 *
 * <p>This method does <em>not</em> report which of these caused the
 * method to return. Callers should re-check the conditions which caused
 * the thread to park in the first place. Callers may also determine,
 * for example, the interrupt status of the thread upon return.
 */
public static void park() {
    UNSAFE.park(false, 0L);
}

park实际上使用的是UNSAFE类里面的park和unpark操作,而LocalSupport仅仅是对UnSafe这个类的功能进行的一些列的封装。
其注释大意为:
在线程调度的时候禁用当前线程,将其放置到WaitSet队列。除非有许可证。所谓的许可证就是前面说的0-1的标识。使用unpark则就会产生一个许可。
如果许可可用,那么使用它并立即返回,否则大昂区线程将被线程调度禁用,处于休眠状态,除非有如下之一的情况发生:

  • 其他线程以当前线程为目标调用unpark方法。
  • 其他线程打断当前线程。
  • 调用了虚假的返回。

该方法不会报告是按个原因导致的方法返回,调用者再次检查造成的原因需要park这个线程,调用者还可以决定线程返回时的中断状态。

2.2 park(Object blocker)

/**
 * Disables the current thread for thread scheduling purposes unless the
 * permit is available.
 *
 * <p>If the permit is available then it is consumed and the call returns
 * immediately; otherwise
 * the current thread becomes disabled for thread scheduling
 * purposes and lies dormant until one of three things happens:
 *
 * <ul>
 * <li>Some other thread invokes {@link #unpark unpark} with the
 * current thread as the target; or
 *
 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 * the current thread; or
 *
 * <li>The call spuriously (that is, for no reason) returns.
 * </ul>
 *
 * <p>This method does <em>not</em> report which of these caused the
 * method to return. Callers should re-check the conditions which caused
 * the thread to park in the first place. Callers may also determine,
 * for example, the interrupt status of the thread upon return.
 *
 * @param blocker the synchronization object responsible for this
 *        thread parking
 * @since 1.6
 */
public static void park(Object blocker) {
    Thread t = Thread.currentThread();
    setBlocker(t, blocker);
    UNSAFE.park(false, 0L);
    setBlocker(t, null);
}

这个方法与park方法类似。但是可以传入一个blocker参数,这个参数表示负责此操作的同步对象的线程。
这个方法与park方法的本质是一样的。只是在调用UNSAFE的park方法之前通过setBlocker方法传入的blocker的表示在当前的线程的内存对象中。

private static void setBlocker(Thread t, Object arg) {
    // Even though volatile, hotspot doesn't need a write barrier here.
    UNSAFE.putObject(t, parkBlockerOffset, arg);
}

同样,setBlocker也是采用UNSAFE.putObject来实现的。

2.3 parkNanos(Object blocker, long nanos)

/**
 * Disables the current thread for thread scheduling purposes, for up to
 * the specified waiting time, unless the permit is available.
 *
 * <p>If the permit is available then it is consumed and the call
 * returns immediately; otherwise the current thread becomes disabled
 * for thread scheduling purposes and lies dormant until one of four
 * things happens:
 *
 * <ul>
 * <li>Some other thread invokes {@link #unpark unpark} with the
 * current thread as the target; or
 *
 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
 * the current thread; or
 *
 * <li>The specified waiting time elapses; or
 *
 * <li>The call spuriously (that is, for no reason) returns.
 * </ul>
 *
 * <p>This method does <em>not</em> report which of these caused the
 * method to return. Callers should re-check the conditions which caused
 * the thread to park in the first place. Callers may also determine,
 * for example, the interrupt status of the thread, or the elapsed time
 * upon return.
 *
 * @param blocker the synchronization object responsible for this
 *        thread parking
 * @param nanos the maximum number of nanoseconds to wait
 * @since 1.6
 */
public static void parkNanos(Object blocker, long nanos) {
    if (nanos > 0) {
        Thread t = Thread.currentThread();
        setBlocker(t, blocker);
        UNSAFE.park(false, nanos);
        setBlocker(t, null);
    }
}

此方法与park方法类似,但是会传入一个过期时间,这个过期时间是以纳秒为单位的。
需要注意的是这个方法如果传入的nanos小于等于0则该方法不会生效。

UNSAFE.park(false, nanos);

可见park方法的第二个参数单位是纳秒。

2.4 parkUntil(Object blocker, long deadline)

/**
 * Disables the current thread for thread scheduling purposes, until
 * the specified deadline, unless the permit is available.
 *
 * <p>If the permit is available then it is consumed and the call
 * returns immediately; otherwise the current thread becomes disabled
 * for thread scheduling purposes and lies dormant until one of four
 * things happens:
 *
 * <ul>
 * <li>Some other thread invokes {@link #unpark unpark} with the
 * current thread as the target; or
 *
 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
 * current thread; or
 *
 * <li>The specified deadline passes; or
 *
 * <li>The call spuriously (that is, for no reason) returns.
 * </ul>
 *
 * <p>This method does <em>not</em> report which of these caused the
 * method to return. Callers should re-check the conditions which caused
 * the thread to park in the first place. Callers may also determine,
 * for example, the interrupt status of the thread, or the current time
 * upon return.
 *
 * @param blocker the synchronization object responsible for this
 *        thread parking
 * @param deadline the absolute time, in milliseconds from the Epoch,
 *        to wait until
 * @since 1.6
 */
public static void parkUntil(Object blocker, long deadline) {
    Thread t = Thread.currentThread();
    setBlocker(t, blocker);
    UNSAFE.park(true, deadline);
    setBlocker(t, null);
}

此方法同样与park方法没有本质的区别,只是多加了一个过期时间的条件。这个过期时间以毫秒为单位。实际上UNSAFE的park方法在这个方法与上个方法之间的差别还有要给就是第一个参数在此处为true。
那么可以猜想就是为true的时候以毫秒为超时单位。为false的时候超时的单位就是纳秒。

2.5 unpark

unpark方法则是之前park方法的授予许可证的过程,如果有许可,那么park调用的时候不会阻塞。

/**
 * Makes available the permit for the given thread, if it
 * was not already available.  If the thread was blocked on
 * {@code park} then it will unblock.  Otherwise, its next call
 * to {@code park} is guaranteed not to block. This operation
 * is not guaranteed to have any effect at all if the given
 * thread has not been started.
 *
 * @param thread the thread to unpark, or {@code null}, in which case
 *        this operation has no effect
 */
public static void unpark(Thread thread) {
    if (thread != null)
        UNSAFE.unpark(thread);
}

调用unpark之后,会将标识变为0,之后park就会被阻塞。
需要注意的是,实际上LocakSupport比较灵活。与wait/notify机制不同的是,其不需要约定先后顺序。也就是说,可以先调用unpark方法。这对于之前wait/notify绝对是巨大的改善。因为wait方法的时候,如果先使用notify,将没有任何效果。一旦用错顺序可以会导致死锁。

3.应用测试

3.1 测试 interrupt

public class LockSupportTest2 {



	public static void main(String[] args) throws InterruptedException{
		Thread t1 = new Thread(new T1(),"T1");
		t1.start();
		TimeUnit.SECONDS.sleep(1);
		t1.interrupt();
		LockSupport.unpark(t1);
	}

	static class T1 implements Runnable {
		@Override
		public void run() {
			while (true) {
				System.out.println(Thread.currentThread().getName()+": print");
				LockSupport.park();
			}
		}
	}
}

上述代码执行结果:

T1: begin loop
T1: print
T1: begin loop
T1: print
...

上述代码会循环执行。不会停止。这是因为,当线程调用interrupt之后,线程就处于interrupt状态。之后的park方法则不会生效。实际上park在interrupt之后不会出现任何异常。

3.2 park & unpark

有了park和unpark之后,我们再回到之前的例子,需要两个线程交替打印1-20,那么这就将非常简单:

public class LockSuppotTest {

	private static volatile int count = 0;

	public static void main(String[] args) throws InterruptedException {

		Thread t1 = new Thread(() -> {
			while (true) {
				System.out.println(Thread.currentThread().getName() + ":" + count++);
				LockSupport.park();
			}
		},"T1");
		Thread t2 = new Thread(() -> {
			while (true) {
				System.out.println(Thread.currentThread().getName() + ":" + count++);
				LockSupport.park();
			}
		},"T2");

		Thread t3  = new Thread(() -> {
			try {
				for(int i=0;i<19;i++){
					TimeUnit.SECONDS.sleep(1);
					if((i&1) == 0) {
						LockSupport.unpark(t1);
					}else {
						LockSupport.unpark(t2);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		},"T3");

		t1.setDaemon(true);
		t2.setDaemon(true);
		t1.start();
		TimeUnit.MILLISECONDS.sleep(100);
		t2.start();
		t3.start();
		t3.join();
		System.out.println("exit!");
	}
}

上述代码执行结果:

T1:0
T2:1
T1:2
T2:3
T1:4
T2:5
T1:6
T2:7
T1:8
T2:9
T1:10
T2:11
T1:12
T2:13
T1:14
T2:15
T1:16
T2:17
T1:18
T2:19
T1:20
exit!

这样就实现了一个不需要通过synchronized或者ReentrantLock的交替打印的例子。

4.总结

LocalSupport也是实现线程间通信的一种有效的方式。而且非常灵活。unpark和park之间不需要有严格的顺序。可以先执行unpark,之后再执行park。这样再编码的过程中就比使用wait/notify方法要简单很多。
此外,LocalSUpport全部是采用UnSafe类来实现的。这个类通过使用park/unpark以及相关cas操作,就实现了java中JUC的各种复杂的数据结构和容器。而且效率非常高。
因此UnSafe及CAS也是后面需要重点说明的部分。

Java多线程系列(五)—LockSupport源码分析 Java多线程系列(五)—LockSupport源码分析 LockSupport类是实现锁机制和其他同步类的基础,提供了基本线程阻塞和恢复的原语; LockSupport中的park() 和 unpark() 的作用分别是阻塞线程和解除阻塞线程,而且park()和unpark()不会遇到“Thread.suspend 和 Thread.resume所可能引发的死锁”问题 阅读详情

相关推荐

Java多线程(14)——JUC——locks系列(1)——LockSupport使用以及源码分析

目录 1.概述 2.LockSupport的park-unpark与Object的wait-notitfy的对比 3.LockSupport的源码分析 3.1 成员变量 3.2 park方法 3.3 unpark方法 1.概述 当我要分析AQS,Condition的时候,发现它们当中都使用到了LockSupport,所以先在这里对LockSupport进行学习 LockSuppo...

波波鱼的博客 571

LockSupport.park() 阻塞住的线程如何唤醒

目录 LockSupport.park() 一:LockSupport.unpark()唤醒线程: 二:中断 不清除中断标记 清除中断标记 LockSupport.park() 或LockSupport.park(Object blocker) 在某个线程中,调用该方法会阻塞住该线程。用park阻塞住的线程,想要唤醒它,有两种方法: 一种是 LockSupport.unpark(),另一种是中断。 一:LockSupport.unpark()唤醒线程: public static v.

mo_ing的博客 2131

缺陷检测:使用PatchCore训练自己的数据集

必须包含有训练图片(无缺陷图片)、测试图片(缺陷图片)和ground_truth,并且ground_truth必须与对应图片的名称相同。同上一篇结果一样,我的输出为原始图片大小,但是不知道是不是因为图片不是正方形的,导致训练结果不好。编写一个脚本,重新规划数据集的路径规则,但是我稍微写复杂了一点,使用了类来操作。第二种(复杂):编写一个自己的Dataset,参考。第一种(简单):将数据集路径规则改成项目中。返回的必须是一个字典类型,可以阅读。本人此次使用的是第一种方法。运行时,参数部分直接输入。

xiaoxTai的博客 6490

Java并发:挂起与唤醒线程LockSupport工具类详解

LockSupport概述 LockSupport工具类定义了一组公共的静态方法,提供了最基本的线程阻塞和唤醒功能,是创建锁和其他同步类的基础,你会发现,AQS中阻塞线程和唤醒线程的地方,就是使用LockSupport提供的park和unpark方法,比如下面这段: // 挂起线程 private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrup

uuuyy_的博客 1387

江科大51单片机笔记【1】单片机及开发板介绍

单片机,Micro Controller Unit,简称MCU,内部集成了CPU、RAM、ROM、定时器、中断系统、通讯接口等一系列电脑的常用硬件功能单片机的任务是信息采集(传感器)、处理(CPU)和硬件设备(电机、LED)的控制单片机算是一个袖珍版计算机,是一个完整的计算机系统,成本低体积小结构简单单片机的使用领域:智能仪表、实时工控、通讯设备、导航系统、家用电器等。

2301_80195807的博客 859

Python+Flask+Echarts打造全国气象数据可视化分析大屏

本文详细介绍了如何使用Python+Flask+Echarts构建全国气象数据可视化分析大屏,实现实时监控、趋势分析和快速决策。通过Python强大的数据处理能力、Flask的轻量级优势和Echarts的交互体验,打造高效的气象数据可视化系统,提升农业、物流等行业的决策效率。

weixin_29061531的博客 1065

java lock park_Java中condition的LockSupport.park(this)是怎么工作的?

有一说一,AQS实在是太复杂了,但我觉得自己勉强还是可以来写个回答。首先是得说LockSupport,LockSupport主要的API就是park和unpark,其实这个类就是对Unsafe的park和unpark的简单封装而已,除此之外还可以用一个blocker 来记录一些和park的发起者有关的信息。这个blocker对于park和unpark来说似乎并没有必要的意义。package jdk...

weixin_39789792的博客 639

Qupath软件的安装与使用

Qupath软件的安装与使用软件安装软件下载软件安装【windows版】简单使用文件打开人工标注标注导出和导入 Qupath是一款开源的医学图像标注软件,适合放射影像及数字病理切片等的查看。同时,其自带的标注功能使得医生可以直接通过该软件进行病变区域的标注和分类。跟进一步的,该软件提供groovy脚本运行接口,可供操作者编写和运行脚本,将标注信息转换为xml或者json格式的数据进行进一步的后序处...

qq_40662074的博客 3万+

Java多线程进阶(4)—— J.U.C之locks框架:LockSupport

LockSupport类,是JUC包中的一个工具类,是用来创建锁和其他同步类的基本线程阻塞原语。park()和unark(),其中park()方法用来阻塞当前调用线程,unpark()方法用于唤醒指定线程。这其实和Object类的wait()和signial()方法有些类似,但是LockSupport的这两种方法从语意上讲比Object类的方法更清晰,而且可以针对指定线程进行阻塞和唤醒。

smart_an的专栏 1120

基于NSGA2算法的无人机三维路径规划MATLAB实现

传统的路径规划方法多采用启发式搜索算法,然而这些方法往往带着局限性,不能有效地克服无人机飞行任务中所遇到的复杂环境与约束。而基于遗传算法的NSGA2(Non-dominated Sorting Genetic Algorithm II)方法则可以在优化目标之间找到最好的平衡点,是一种十分优秀的解决方案。本文介绍了基于NSGA2算法的无人机三维路径规划MATLAB实现。NSGA2算法是一种多目标优化算法,通过非支配排序和拥挤度距离来评估个体的适应度和选择新个体,从而产生一组非支配解。3.选择新个体组成P1;

CyberLynxX的博客 984

【DEIM创新改进】全网独家创新、注意力改进篇 | AAAI 2026 | DEIM 引入轻量级群体注意力(LWGA)模块,可以显著提高其多尺度物体检测能力,特别是在小物体和复杂背景下的表现

本文提出了一种改进的DEIM网络模型,通过引入轻量级LWGA模块显著提升了多尺度物体检测性能。LWGA模块采用局部和全局注意力机制,有效提升了小物体和复杂背景下的识别能力,同时保持低计算成本。该模块通过分割输入特征图并应用多种注意力机制(GPA、RLA、SMA、SGA)进行特征提取和融合,优化了多尺度物体的特征表示。实验表明,改进后的DEIM模型在遥感图像处理等任务中表现出色,在12个数据集上实现了性能与计算效率的最佳平衡,为资源受限设备提供了高效的解决方案。

Ai缝合怪、助力小伙伴高效发论文 277

白话java锁--LockSupport

通过前面几篇文章的分析,

weixin_44936828的博客 372

华为防火墙——本地Portal认证

配置IP地址、路由、Nat策略使得内网主机可以访问公网服务器对网段不进行认证,对网段进行portal认证。

m0_49864110的博客 3270

LockSupport常用方法源码分析

本文将介绍LockSupport类中的方法和部分源码,以及面试常问到的一个小问题,感兴趣的大佬可以指点下。

小威的博客 3万+

ORB-SLAM3算法2之EuRoc开源数据集运行ORB-SLAM3生成轨迹并用evo工具评估轨迹

ORB-SLAM3算法1 已成功编译安装ORB-SLAM3到本地,本篇目的是用EuRoc开源数据来运行ORB-SLAM3,并生成轨迹,最后用evo评估工具来评估ORB-SLAM3生成的轨迹和真值轨迹。

重点记录机器人和自动驾驶相关领域的技术,尤其是计算机视觉,视觉SLAM等,不仅有前言文献或必备算法的学习,也会有实际应用的点滴经验 3764

深度学习工具包 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")

LockSupport使用及源码详解

LockSupport使用及源码详解 在讲了一批并发工具后,突然想起LockSupport类了,这个工具类我也很少用,所以这次写了个小demo后,决定也写一篇文章记录一下,以下就是记录过程。 LockSupport用法 在网上随便找了个演示demo,如下: public class LockSupportDemo { public static void main(String[] a...

u012734441的专栏 2589

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

LockSupport详解

前言 LockSupport是concurrent包中一个工具类,不支持构造,提供了一堆static方法,比如park(),unpark()等。 LockSupport中的主要成员及其加载时的初始化: 不难发现,他们在初始化的时候都是通过Unsafe去获得他们的内存地址,这里也可以理解为C中的指针。 Unsafe Unsafe类可以参考我之前写的文章:深入理解sun.misc.Unsafe原理 ...

Deegue 1万+

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

LockSupport 深入源码解析

  LockSupport是一个线程工具类,所有的方法都是静态方法,可以在线程任意位置阻塞、唤醒线程。LockSupport的功能是依赖Unsafe类实现的。   演示示例: package com.securitit.serialize.locks; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; public class LockSupportTester { public

键盘上流淌的日子 7821

Java多线程编程-LockSupport工具类使用及源码分析

Java多线程编程-LockSupport工具类使用及源码分析LockSupport类LockSupport.park()1.调用unpack方法获得许可2.调用中断interrupts方法获得许可parkNanos(long nanos)park(Object blocker)parkNanos(Object blocker, long nanos)parkUntil(Object blocker, long deadline) 在Java工具包中有一个LockSupport工具类,主要负责挂起和唤醒线程

HQ DevJ的专栏 859

LockSupport 详解及源码分析

LockSupport是Java并发包中的核心工具类,提供线程阻塞(park)和唤醒(unpark)能力。相比wait/notify机制,它无需同步块、支持精准线程控制、具有许可机制(先唤醒后阻塞不卡死)和更好的中断处理。其核心是通过二元许可(0/1)控制线程状态,park消耗许可,unpark设置许可。底层使用Unsafe类实现,最终通过操作系统原语(如Linux的futex)挂起/唤醒线程。LockSupport是构建高级同步器的基础,具有更灵活、更可靠的线程控制能力。

csdn_tom_168的博客 1260

多线程——LockSupport

一、初步认识 LockSupport 是一个灵活的线程工具类,主要是为了阻塞和唤醒线程用的,查看 API 或 源码可知,它的所有方法都是静态方法 // 阻塞当前线程 / 禁止当前线程调度,除非许可证可用 public static void park(Object blocker) // 暂停当前线程,有超时时间 / 禁用当前线程进行线程调度,直到指定的等待时间,除非许可证可用 public static void parkNanos(Object blocker, long nanos) //

weixin_41960204的博客 240

LockSupport详解:Java并发编程的基石

是用来创建锁和其他同步类的基本线程阻塞原语。它提供了一组静态方法,让线程可以阻塞(park)和唤醒(unpark)。阻塞方式锁释放使用位置唤醒方式适用场景不释放任意自动简单延时释放synchronized块notify线程间通信释放lock.lock()后signal高级锁不释放任意unpark底层工具知识点一句话总结核心功能线程阻塞(park)和唤醒(unpark)的基本原语底层实现基于Unsafe的park/unpark native方法许可机制。

✨ 欢迎来到【Seal ^_^ 的CSDN博客】!✨ 3116

源码解读(三):Java中的LockSupport的使用

Java中的LockSupport的使用1、LockSupport方法介绍对比park() 与park(Object blocker) 的区别parkUntil(long deadline) 方法的时间点在哪里2、LockSupport源码及注释3、关于sun.misc.Unsafe类型 1、LockSupport方法介绍 在Java多线程中,当需要阻塞或唤醒一个线程时,我们可以使用LockSup...

A_finder的博客 769

大话JUC核心类LockSupport(通过源码理解LockSupport)

LockSupport简介 LockSupport是创建锁和其他同步类的基本线程阻塞原语。它的方法都是静态方法,可以让线程在任意位置阻塞,也可以在任意位置唤醒。 简而言之,当调用LockSupport.park时,表示当前线程将会等待,直至获得许可,当调用LockSupport.unpark时,必须把等待获得许可的线程作为参数进行传递,好让此线程继续运行。 LockSupport源码分析 删除了官方注释 package java.util.concurrent.locks; // java 实现线程

qq_26462567的博客 1286

【并发编程】LockSupport源码详解

一篇文章带你搞懂LockSupport,从底层源码详细剖析其实现原理。面试再也不怕LockSupport。

小七的博客 1472

LockSupport源码阅读

本人的源码阅读主要聚焦于类的使用场景,一般只在java层面进行分析,没有深入到一些native方法的实现。并且由于知识储备不完整,很可能出现疏漏甚至是谬误,欢迎指出共同学习相比mutex这个概念来说,LockSupport更像是信号量,不过与信号量最大区别在于LockSupport的"资源计数"最大只有1,叫做,下面直接介绍两个核心方法park和unpark,其他的方法基本都是基于这两个方法重载或扩展而来。

qq_36769368的博客 893
上一篇: 多线程基础(九):守护线程、yield、join及线程组
下一篇: 一道多线程协同面试题的三种解决方案
冬天里的懒猫
博客等级 码龄18年 129粉丝 176原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值