java并发编程实战wwj———————-第一阶段————–27-28-29-30

java并发编程实战wwj———————-第一阶段————–27-28-29-30代码:chapter9sleep:是Threa的方法,sleep不释放锁,sleep不用synchronized,不需要被唤醒。wait:所有对象的方法,wait释放锁,用synchronized,要被唤醒。如何使用这个案例:切换m1和m2方法。packagechapter9;importjava.util.stream.Stream;/************…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

代码:chapter9

java并发编程实战wwj----------------------第一阶段--------------27-28-29-30

sleep:是Thread的方法,sleep不释放锁,sleep不用synchronized,不需要被唤醒。

wait:所有对象的方法,wait释放锁java并发编程实战wwj----------------------第一阶段--------------27-28-29-30,

用synchronized,要被唤醒。

java并发编程实战wwj----------------------第一阶段--------------27-28-29-30

如何使用这个案例:切换m1和m2方法。

chapter9


package one.chapter9;

import java.util.stream.Stream;


public class DifferenceOfWaitAndSleep {

    private final static Object LOCK = new Object(); // 定义锁一定要定义final类型的

    public static void main(String[] args) {
        Stream.of("T1", "T2").forEach(name ->
                new Thread(name) {
                    @Override
                    public void run() {
                        m1();
                    }
                }.start()
        );
    }

    public static void m1() {
        synchronized (LOCK) {
            try {  
                System.out.println("The Thread " + Thread.currentThread().getName() + " enter.");
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void m2() {
        synchronized (LOCK) {
            try {
                System.out.println("The Thread " + Thread.currentThread().getName() + " enter.");
                LOCK.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

—————————————-27———–sleep和wait的区别——————-

先start之后才可以join。先设置守护线程才可以start。

java并发编程实战wwj----------------------第一阶段--------------27-28-29-30线程的数量的优化图,多了上下文就多了会有开销的。

卡了看看是不是线程太多了。

jdk8的::https://blog.csdn.net/csmans/article/details/82256690

—

问题:10000台机器如何用100个线程采集,线程多了会有问题,上下文切换。

代码:

java并发编程实战wwj----------------------第一阶段--------------27-28-29-30

package one.chapter9;

import java.util.*;

public class CaptureService {

    final static private LinkedList<Control> CONTROLS = new LinkedList<>();
    private final static int MAX_WORKER = 5;

    public static void main(String[] args) {

        List<Thread> worker = new ArrayList<>();
        Arrays.asList("M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10").stream()
                .map(CaptureService::createCaptureThread)
                .forEach(t -> {
                    t.start();
                    worker.add(t);
                });
        // 在这里去通体的join
        worker.stream().forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Optional.of("All of capture work finished").ifPresent(System.out::println);
    }


    private static Thread createCaptureThread(String name) {
        return new Thread(() -> {
            Optional.of("The worker [" + Thread.currentThread().getName() + "] BEGIN capture data.")
                    .ifPresent(System.out::println);
            synchronized (CONTROLS) {
                while (CONTROLS.size() > MAX_WORKER) {//要是有5个就乖乖等着就可以
                    try {
                        CONTROLS.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                CONTROLS.addLast(new Control());//跳出while就说明可以跑了加入跑的队列  对公共数据操作要串行化保护的
            }

            // 这个是并行的
            Optional.of("The worker [" + Thread.currentThread().getName() + "] is working...")
                    .ifPresent(System.out::println);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {//采集时间是10S  并行去执行任务

                e.printStackTrace();
            }

            synchronized (CONTROLS) {//工作完了我吧自己移除工作队列
                Optional.of("The worker [" + Thread.currentThread().getName() + "] END capture data.")
                        .ifPresent(System.out::println);
                CONTROLS.removeFirst();// 为什么remove
                // first?删掉的可能是自己也肯能是别人只要删掉就可以了 其实
                CONTROLS.notifyAll();
            }
        }, name);
    }

    private static class Control {
    }
}

对公共数据的操作要设置同步的保护的,这是真理。

——————————28———-控制并发————————-

自定义的锁解决synchronized的慢的问题:

代码chapter10

代码:

java并发编程实战wwj----------------------第一阶段--------------27-28-29-30

第一步:写一个接口

定义显示锁:


public interface Lock {

    class TimeOutException extends Exception {
        public TimeOutException(String message) {//报错信息
            super(message);
        }
    }

    void lock() throws InterruptedException;//加锁

    void lock(long mills) throws InterruptedException, TimeOutException;//没有获取到锁就退出来了

    void unlock();//释放锁

    Collection<Thread> getBlockedThread();//获得被阻塞的线程

    int getBlockedSize();//获得被阻塞的线程的个数

}

先看下最终的代码

package one.chapter10;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;

public class BooleanLock implements Lock {

    //The initValue is true indicated the lock have be get.
    //The initValue is false indicated the lock is free (other thread can get this.)
    private boolean initValue;

    // 被阻塞的线程
    private Collection<Thread> blockedThreadCollection = new ArrayList<>();

    private Thread currentThread;//为什么第一这个变量,谁加的锁只能由谁去释放的。

    public BooleanLock() {
        this.initValue = false;
    }

    @Override
    public synchronized void lock() throws InterruptedException {
        while (initValue) {//true就是我不能抢到锁了就得等着
            if(!blockedThreadCollection.contains(Thread.currentThread())){
                blockedThreadCollection.add(Thread.currentThread());
            }
            this.wait();// 就在lock上wait
        }
        blockedThreadCollection.remove(Thread.currentThread());
        this.initValue = true;
        this.currentThread = Thread.currentThread();//设置lock是当前的线程虽然抢锁失败了
    }

    @Override
    public synchronized void unlock() {//这个synchronized锁的是BooleanLock的实例
        if (Thread.currentThread() == currentThread) {//是当前的线程才释放的
            this.initValue = false;
            Optional.of(Thread.currentThread().getName() + " release the lock monitor.")
                    .ifPresent(System.out::println);
            this.notifyAll();
        }
    }

       @Override
    public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
        if (mills <= 0)
            lock();
        long hasRemaining = mills;//需要等的时间
        long endTime = System.currentTimeMillis() + mills;//到什么时间结束
        while (initValue) {//需要等待   醒了我就去抢锁,抢不到我就加时间  多次醒了请不到我就超时了 我直接抛出异常了
            if (hasRemaining <= 0)
                throw new TimeOutException("Time out");
            if(!blockedThreadCollection.contains(Thread.currentThread())){
                blockedThreadCollection.add(Thread.currentThread());
            }
            this.wait(mills);
            hasRemaining = endTime - System.currentTimeMillis();
        }
        blockedThreadCollection.remove(Thread.currentThread());
        this.initValue = true;
        this.currentThread = Thread.currentThread();
    }

    /**
     * 注意这个要考线程安全 其他的线程可以在其他的方法操作这个集合
     * @return
     */
    @Override
    public Collection<Thread> getBlockedThread() {
        return Collections.unmodifiableCollection(blockedThreadCollection);
    }

    @Override
    public int getBlockedSize() {
        return blockedThreadCollection.size();
    }
}

———-29——————————–

第一个一个bug:

java并发编程实战wwj----------------------第一阶段--------------27-28-29-30

t1加的锁只能t1去释放,其他的是不能去释放的。

  @Override
    public synchronized void lock() throws InterruptedException {
        while (initValue) {//true就是我不能抢到锁了就得等着
            if(!blockedThreadCollection.contains(Thread.currentThread())){
                blockedThreadCollection.add(Thread.currentThread());
            }
            this.wait();
        }

        blockedThreadCollection.remove(Thread.currentThread());
        this.initValue = true;
        this.currentThread = Thread.currentThread();//Thread.currentThread()这个是获取到锁的线程
    }

    @Override
    public synchronized void unlock() {//这个synchronized锁的是BooleanLock的实例
        if (Thread.currentThread() == currentThread) {//是当前的线程才释放的
            this.initValue = false;
            Optional.of(Thread.currentThread().getName() + " release the lock monitor.")
                    .ifPresent(System.out::println);
            this.notifyAll();
        }
    }

第二个问题:synchronized不能打断,导致等待时间长,这个是synchronized的工作机制。

package chapter10;


public class SynchronizedProblem {

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

        new Thread() {
            @Override
            public void run() {
                SynchronizedProblem.run();
            }
        }.start();

        Thread.sleep(1000);

        Thread t2 = new Thread() {
            @Override
            public void run() {
//                /sdfsdfsd
                SynchronizedProblem.run();
                //sdfsdfsd
                System.out.println("继续做以下的事情t");
            }
        };
        t2.start();
        Thread.sleep(2000);
        t2.interrupt();
        System.out.println(t2.isInterrupted());
    }

    private synchronized static void run() {
        System.out.println(Thread.currentThread());
        while (true) {

        }
    }
}

t2可以打断但是不能中断进入java并发编程实战wwj----------------------第一阶段--------------27-28-29-30

t2是一直block住的。我们不能让t2释放回来。做线程的其他的事情。

java并发编程实战wwj----------------------第一阶段--------------27-28-29-30我们要解决这个问题。

    @Override
    public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
        if (mills <= 0)
            lock();
        long hasRemaining = mills;//需要等的时间
        long endTime = System.currentTimeMillis() + mills;//到什么时间结束
        while (initValue) {//需要等待   醒了我就去抢锁,抢不到我就加时间  多次醒了请不到我就超时了 我直接抛出异常了
            if (hasRemaining <= 0)
                throw new TimeOutException("Time out");
            if(!blockedThreadCollection.contains(Thread.currentThread())){
                blockedThreadCollection.add(Thread.currentThread());
            }
            this.wait(mills);
            hasRemaining = endTime - System.currentTimeMillis();
        }
        blockedThreadCollection.remove(Thread.currentThread());
        this.initValue = true;
        this.currentThread = Thread.currentThread();
    }

——————————-30——————————-

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/188765.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • SpringMVC笔记(3)

    SpringMVC笔记(3)

    2021年11月12日
  • layui弹出层html,layui弹出层效果实现代码

    layui弹出层html,layui弹出层效果实现代码本文实例为大家分享了layui弹出层的具体代码,供大家参考,具体内容如下弹出层大部分演示都在layer独立组件的官网,与内置的layer模块,用法是完全一致的特殊例子Tips:为了更清晰演示,每触发下述一个例子之前,都会关闭所有已经演示的层多窗口模式,层叠置顶配置一个透明的询问框示范一个公告层上弹出右弹出下弹出左弹出左上弹出左下弹出右上弹出右下弹出居中弹出Layui-精心为你雕琢layui.u…

    2022年5月2日
  • Android 极简反射教程及应用示例

    Android 极简反射教程及应用示例

    2021年9月16日
  • 值得推荐的Idea十几大优秀插件

    值得推荐的Idea十几大优秀插件最近,闲来无事,为了改变一下枯燥的编程环境,特地搜寻了下有助提升代码功力的插件,够装逼,够狂,拽,屌~绚丽的画面,多彩的跳动,让你区别其他程序猿。产品,测试,开发看到你的界面,眼睛都会发光~算了,我实在是编不下去,自己去体验吧~PS:☆半星★一星主要是以狂拽屌指数来排名12、Stackoverflow这个插件其实是最实用的插件,程序猿遇到的问题…

    2022年6月16日
  • 微服务 eureka_变压吸附的原理

    微服务 eureka_变压吸附的原理文章目录前言一、Eureka是什么?二、Eureka是干什么的?1.服务治理三、Eureka原理解析1.总体流程2.读入数据总结前言       随着互联网技术的发展,系统用户量的增长,很多系统都采用了分布式的方式进行部署。这个固然大大提高了系统的性能和可用性,但是分布式部署导致各种服务数量大增,这给我们进行服务治理和运维带来了困扰。一、Eureka是什么?     &nbsp

    2022年4月19日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号