leader/follower多线程模型

上图就是L/F多线程模型的状态变迁图,共6个关键点:

(1)线程有3种状态:领导leading,处理processing,追随following

(2)假设共N个线程,其中只有1个leading线程(等待任务),x个processing线程(处理),余下有N-1-x个following线程(空闲)

(3)有一把锁,谁抢到就是leading

(4)事件/任务来到时,leading线程会对其进行处理,从而转化为processing状态,处理完成之后,又转变为following

(5)丢失leading后,following会尝试抢锁,抢到则变为leading,否则保持following;

(6)following不干事,就是抢锁,力图成为leading


简单代码实现:

public class ThreadPool {
	private final static Object monitor = new Object();
	private final static int THREAD_POO_SIZE = 5;

	private Reactor handleSet = new Reactor();

	public ThreadPool(Reactor handleSet) {
		this.handleSet = handleSet;
	}

	public void init() {
		for (int i = 0; i < THREAD_POO_SIZE; i++) {
			new WorkThread(this).start();
		}
		this.promoteNewLeader();
	}

	public void join() {
		for (;;) {
			waitToLeader();
			// select, blocking
			Handle handle = handleSet.select();

			// promote new leader
			promoteNewLeader();

			// process handl
			handleSet.handle(handle);

			// reenter to next loop
		}
	}

	private void waitToLeader() {
		synchronized (monitor) {
			try {
				monitor.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void promoteNewLeader() {
		synchronized (monitor) {
			monitor.notify();
		}
	}

	class WorkThread extends Thread {
		ThreadPool tp;

		public WorkThread(ThreadPool tp) {
			this.tp = tp;
		}

		@Override
		public void run() {
			tp.join();
		}

	}
}

spserver高并发服务器已经利用lf模式实现


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值