不加锁交替执行线程的两种思路(递加取余判断、环形链表步进)(无锁,存在线程安全问题,在此仅作为一种思路分享)

31 篇文章 0 订阅
5 篇文章 0 订阅


思考:为何递加取余的打印的顺序乍一看好像不是顺序打印,实际上是按顺序交替打印的,怎么优化?可以参考这篇文章的第4节:[13行代码实现两个线程交替打印](https://blog.csdn.net/u010425839/article/details/122502217)******

一、递加取余判断(无锁,存在线程安全问题,在此仅作为一种思路分享)

  1. 首先定义一个整型变量;
  2. 每次执行时加一;
  3. 根据【对2取余后的余数】来决定执行哪个线程任务;
  4. 执行代码如下:
public class AlternatePrintOdevity1 {
	private static int step = 0;
	//【1】通过递加求余判断,确保线程交替执行
	public static void task(int max,int remainder){
		while(step<=max) {
			if(step%2==remainder) {		
				System.out.println(Thread.currentThread().getName() + step++);			
			}
		}
	}	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(()->{
			task(10,0);
		},"T1#");
		Thread t2 = new Thread(()->{
			task(10,1);
		},"T2#");
		t1.start();t2.start();	
	}
}

二、环形链表步进(无锁,存在线程安全问题,在此仅作为一种思路分享)

  1. 首先定义一个有两个节点的环形链表,两个节点互为对方的下一节点;
  2. 每次执行后步进到next下一节点;
  3. 根据【当前节点是否为想要的节点】来决定执行哪个线程任务;
  4. 执行代码如下:
class Node{ 
	Node next;
}
public class AlternatePrintOdevity2 {
	private static int step = 0;
	private static Node node1 = new Node();
	private static Node node2 = new Node();
	private static Node curr = node1;
	static{
		node1.next = node2;
		node2.next = node1;
	}
	public static void task(int max,Node wantedNode){
		while(step<=max){	
			if(wantedNode==curr) {
				System.out.println(Thread.currentThread().getName() + step++);
				curr = curr.next;					
			}	
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(()->{
			task(10,node1);
		},"T1#");
		Thread t2 = new Thread(()->{
			task(10,node2);
		},"T2#");
		t1.start();t2.start();	
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Dylanioucn

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

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

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

打赏作者

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

抵扣说明:

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

余额充值