java并发LockSupport
Posted juncaif
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java并发LockSupport相关的知识,希望对你有一定的参考价值。
java并发LockSupport
LockSupport是阻塞和唤醒线程的重要类。
park()方法使得当前线程阻塞
unpark(Thread thread)唤醒线程
例子
可以把注释取消再执行,就会发现park()方法使得当前线程阻塞会使得main线程阻塞,无法结束。
package com.java.javabase.thread.base.concurrent.lock;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.LockSupport;
@Slf4j
public class LockSupportTest
/**
* @author
* @version
* @since
*/
private static Object object = new Object();
private static int size = 10;
private static int sum = 0;
public static void main(String[] args)
Thread t1 = new Thread()
@Override
public void run()
for (int i = 0; i < size; i++)
sum += i;
LockSupport.park();
log.info(" sum :", Thread.currentThread().getName(),sum);
;
Thread t2 = new Thread()
@Override
public void run()
for (int i = 0; i < size; i++)
sum += i;
log.info(" sum :",Thread.currentThread().getName(), sum);
;
t1.start();
//t2.start();
log.info("current thread is ",Thread.currentThread().getName());
//LockSupport.park(t2);
LockSupport.unpark(t1);
//LockSupport.unpark(t2);
结果
2019-08-09 11:40:15,219 [main] INFO LockSupportTest - current thread is main
2019-08-09 11:40:15,219 [Thread-0] INFO LockSupportTest - Thread-0 sum :45
以上是关于java并发LockSupport的主要内容,如果未能解决你的问题,请参考以下文章