码迷,mamicode.com
首页 > 编程语言 > 详细

java并发LockSupport

时间:2019-08-09 13:34:10      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:rgs   getname   support   ide   err   thread   static   java并发   ring   

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

标签:rgs   getname   support   ide   err   thread   static   java并发   ring   

原文地址:https://www.cnblogs.com/JuncaiF/p/11326297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!