多线程模拟选举

package com.activiti6.cmd;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * n个线程进行选举,当某个线程成为master之后结束线程,然后n-1个线程继续选举。。。。。
 * 用一个全局类监控整个程序的状态
 */
public class Master {
    volatile  static Thread master;
    static Object mainStop =new Object();
    static Object threadStop=new Object();

    public static void main(String[] args) throws InterruptedException {
        int n=1000;
        ReentrantLock lock=new ReentrantLock();
        LatchHolder holder=new LatchHolder();
        holder.setRunningCount(new AtomicInteger(n));
        holder.setParticipeCount(new AtomicInteger(n));

        List<Thread> threads=new ArrayList<>();
        for(int i=0;i<n;++i){
            Object obj=new Object();
            MyThead myThead=new MyThead(holder,lock,obj);
            threads.add(myThead);
            holder.getMap().put(myThead,obj);


        }
        for(Thread t:threads){
            t.start();
        }

        for(int i=1;i<=n;++i) {
            Master.master = null;
            holder.setMainShouldWait(true);
            holder.signAllThread();
            synchronized (mainStop) {
                while (holder.isMainShouldWait() == true) {
                    mainStop.wait();
                }

            }




        }

    }
}
class LatchHolder{
     AtomicInteger runningCount;

     AtomicInteger participeCount;

     boolean mainShouldWait =false;

     ConcurrentHashMap<Thread,Object> map=new ConcurrentHashMap();

    public boolean isMainShouldWait() {
        return mainShouldWait;
    }

    public void setMainShouldWait(boolean mainShouldWait) {
        this.mainShouldWait = mainShouldWait;
    }

    public AtomicInteger getRunningCount() {
        return runningCount;
    }

    public void setRunningCount(AtomicInteger runningCount) {
        this.runningCount = runningCount;
    }

    public AtomicInteger getParticipeCount() {
        return participeCount;
    }

    public void setParticipeCount(AtomicInteger participeCount) {
        this.participeCount = participeCount;
    }

    public ConcurrentHashMap<Thread, Object> getMap() {
        return map;
    }

    public void setMap(ConcurrentHashMap<Thread, Object> map) {
        this.map = map;
    }

    public void signAllThread(){
        synchronized (Master.threadStop) {
            Set<Object> conditions = new HashSet<>();
            for (Map.Entry<Thread, Object> e : map.entrySet()) {
                conditions.add(e.getValue());

            }
            this.map.clear();
            Master.threadStop.notifyAll();    ;
        }
//        for(Object condition:conditions){
//            synchronized (condition) {
//                condition.notify();
//            }

    }

    public  void countdow(){
        synchronized (Master.mainStop) {
            int atomcount = getRunningCount().decrementAndGet();
            if (atomcount == 0) {
                getParticipeCount().decrementAndGet();
                getRunningCount().set(getParticipeCount().get());
                setMainShouldWait(false);

                Master.mainStop.notify();

            }
        }
    }
}
class MyThead extends Thread{
    LatchHolder holder;
    ReentrantLock lock;
    Object mycontion;

    public MyThead(LatchHolder holder,ReentrantLock lock,Object mycontion){
        this.holder=holder;
        this.lock=lock;
        this.mycontion=mycontion;
    }

    @Override
    public void run() {
        while (true){
            Object mylock=null;
            /**
             * 如果把synchronized放在循环里面有可能出现
             * thread1                                                          main
             * mylock = holder.getMap().get(Thread.currentThread()
             *                                                                  进入同步块remove并且notify
             * 进入同步块wait(以后没人唤醒)
             */
            synchronized (Master.threadStop) {
                while ((mylock = holder.getMap().get(Thread.currentThread())) != null) {
                    try {

                        Master.threadStop.wait();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            Boolean getlock= lock.tryLock();
//            System.out.println(getlock);
            if(getlock){
                if(Master.master==null){
                    Master.master=Thread.currentThread();
                    System.out.println(Thread.currentThread().getId());
                    holder.getMap().remove(Thread.currentThread());
//                    lock.unlock();
                    holder.countdow();
                    lock.unlock();
                    return;
                }else{
                    lock.unlock();
                }

            }else{
            }
            holder.countdow();
            holder.getMap().put(Thread.currentThread(),mycontion);

        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值