首页 > 代码库 > 多线程交替执行
多线程交替执行
package com.xsz.demo; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 兩個線程交替執行 * @author cwqi */ public class AdvanceMutiThread { public static void main(String[] args) { final ThreadTest5 threadTest5 = new ThreadTest5(); final int count = 5; new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < count; i++) { threadTest5.addMethod(); } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < count; i++) { threadTest5.subtractMethod(); } } }).start(); } } class ThreadTest5 { private Lock lock = new ReentrantLock(); private int cons = 0; int flag = 0; Condition con1 = lock.newCondition(); Condition con2 = lock.newCondition(); public void addMethod() { // 執行加1 lock.lock(); try { while (flag % 2 != 0) con1.await(); System.out.println("Thread A: " + (++cons)); flag++; con2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void subtractMethod() { // 執行減1 lock.lock(); try { while (flag % 2 == 0) con2.await(); System.out.println("Thread B: " + (--cons)); flag++; con1.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
多线程交替执行
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。