Java 多线程中两个线程交替执行输出奇偶数的三种实现方法

本文介绍了在多线程环境下,使用synchronizedwaitnotify、ReentrantLock+Condition及AtomicInteger+volatile三种方法实现交替打印奇偶数的详细代码示例。通过对比不同同步机制的运用,帮助读者理解多线程编程中的锁机制和条件变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初次总结,有欠缺的地方还请大佬指正

方法一:synchronized wait notify

//synchronized wait notify

public class alternateOutWay1 {

	public static void main(String[] args) {

		alternateOutWay1Class cu = new alternateOutWay1Class();

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				cu.getOdd();
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				cu.getEven();
			}
		}).start();

	}
}

class alternateOutWay1Class {

	public synchronized void getOdd() {

		for (int i = 0; i <= 100; i += 2) {
			System.out.println(Thread.currentThread().getName() + "  " + i);
			this.notify();
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (i > 100) {
				this.notify();
			}
		}
		this.notify();
	}

	public synchronized void getEven() {

		for (int i = 1; i <= 100; i += 2) {
			System.out.println(Thread.currentThread().getName() + "  " + i);
			this.notify();
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.notify();
	}
}

方法二:ReentrantLock + Condition


import java.util.concurrent.locks.ReentrantLock;
/**
 * 
 * @author chain
 * 
 * ReentrantLock + Condition
 * 
 */
public class alternateOutWay2 {

	public static void main(String[] args) {
		alternateOut cu = new alternateOut();

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for (int i = 0; i < 50; i++) {
					cu.outputOdd();
				}
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for (int i = 0; i < 51; i++) {
					cu.outputEven();
				}
			}
		}).start();

	}

}

class alternateOut {

	private static int i = 0;
	private static boolean flagB = false;
	private ReentrantLock lock = new ReentrantLock();
	private Condition con = lock.newCondition();
	private Condition con1 = lock.newCondition();

	public void outputOdd() {
		lock.lock();
		try {
			if (!flagB) {
				con1.await();
			}
			System.out.println(Thread.currentThread().getName() + "   A   " + i++);
			flagB = false;
			con.signal();
			
			if(i > 100) {
				con1.signal();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void outputEven() {
		lock.lock();
		try {
			if (flagB) {
				con.await();
			}
			System.out.println(Thread.currentThread().getName() + "   B   " + i++);
			flagB = true;
			con1.signal();
			//这一步是为了将线程正常结束
			if(i > 100) {
				con.signal();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}

方法三:AtomicInteger + volatile

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * @author chain
 * 
 * AtomicInteger + volatile
 *
 * 注意一点:incrementAndGet 和 getAndincrement是不一样的
 */
public class alternateOutWay3 {

	private static AtomicInteger cxsNum = new AtomicInteger(0);
	
	private volatile static boolean flag = false;
	
	public static void main(String[] args) {
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for(;100>cxsNum.get();) {
					if(!flag && (cxsNum.get() ==0 || cxsNum.incrementAndGet() % 2 == 0)) {
						try {
							TimeUnit.MILLISECONDS.sleep(10);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName()+"  "+cxsNum.get());
						flag = true;
					}
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for(;100>cxsNum.get();) {
					if(flag && cxsNum.incrementAndGet() % 2 != 0) {
						try {
							TimeUnit.MILLISECONDS.sleep(10);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName()+"  "+cxsNum.get());
						flag = false;
					}
				}
			}
		}).start();
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yann.bai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值