栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

并发编程-Day04

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

并发编程-Day04

一、
1.1 wait和notify
线程wait会释放锁进入waitSet等待,owner线程使用notify会唤起等待队列的线程进入EntryList继续参与竞争。

 new Thread(()->{
            synchronized (object){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                object.notify();
            }
        }).start();
      synchronized (object){
          object.wait();
          log.debug("被唤醒");
      }

其他线程唤醒主线程

1.2 sleep和wait
sleep在休眠不会释放锁,wait进入waitset会释放锁

二、
2.1 保护性暂停模式(join 的实现、Future 的实现,采用的就是此模式)
一个线程需要另一个线程的结果时,需要关联同一个GuardedObject对象。

@Slf4j(topic = "c.Test01")
public class Test01 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        GuardedObject object = new GuardedObject();
        new Thread(()->{

            Object o = object.get();
            log.debug("获取到数据");
            log.debug("数据是{}",o);
        }).start();

        new Thread(()->{
            log.debug("下载数据");
            object.set(1234536L);
        }).start();

    }


    }
@Slf4j(topic = "c.Test01")
class GuardedObject {
    private Object response;

    public Object get() {
        synchronized (this) {
            while (response == null) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

    @SneakyThrows
    public void set(Object o){
        synchronized (this){
            Thread.sleep(3000);
            this.response = o;
            this.notifyAll();
        }
    }
}


结果:

在多个类中使用GuardedObjec很不方便,不能进行多个任务管理,需要引入Future

@Slf4j(topic = "c.Test01")
public class Test01 {

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

        for (int i = 0; i < 3; i++) {
            new People().start();
        }//首先是三个人等待收信,都有对应的GuardedObject
        Thread.sleep(1000);
        //收集所有需要执行的任务
        Set ids = MailBox.getIds();
        for (Integer id : ids) {
        //指派邮递员送信
            new PostMan(id,"内容"+id).start();
        }

    }


    }

    @Slf4j(topic = "c.people")
class People extends Thread{
    @Override
    public void run() {
        //收信

        log.debug("开始收信");
        GuardedObject guardedObject = MailBox.createGuardedObject();
        Object mail = guardedObject.get(2000);
        log.debug("收到信:{}",mail);
    }
}
@Slf4j(topic = "c.postman")
class PostMan extends Thread{
    private int id;
    private String msg;
    public PostMan(int id,String msg){
        this.id = id;
        this.msg = msg;
    }
    @Override
    public void run() {
        GuardedObject guardedObject = MailBox.getGuardedObjectById(id);
        log.debug("拿到信{},{}",id,msg);
        guardedObject.set(msg);
        log.debug("送信完成");
    }
}
class MailBox{
    private static Hashtable table = new Hashtable<>();//使用hashtable存放,hashtable是线程安全的

    private static int i = 0;

    private static synchronized int generateId(){
        return i++;
    }
    public static GuardedObject getGuardedObjectById(int id){
        return table.remove(id);//每次快递员拿完信需要删除,防止占用内存
    }
    public static GuardedObject createGuardedObject(){
        GuardedObject guardedObject = new GuardedObject(generateId());
        table.put(guardedObject.getId(),guardedObject);
        return guardedObject;
    }

    public static Set getIds(){
        return table.keySet();
    }
}

@Slf4j(topic = "c.Test01")
class GuardedObject {
    private Object response;
    private Integer id;

    public GuardedObject(Integer id){
        this.id = id;
    }

    public Integer getId() {
        return id;
    }


    public Object get(long timeOut) {
        long begin = System.currentTimeMillis();
        long passTime = 0L;
        long waitTime = timeOut;
        synchronized (this) {
            while (response == null) {
                waitTime = waitTime-passTime;
                if(waitTime <= 0)
                {
                    log.debug("超时了");
                    break;
                }
                try {
                    this.wait(waitTime);
                    log.debug("等待结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            passTime = System.currentTimeMillis()-begin;
        }
        return response;
    }

    @SneakyThrows
    public void set(Object o){
        synchronized (this){
            Thread.sleep(6000);
            this.response = o;
            this.notifyAll();
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/927254.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号