不加锁交替执行线程的两种思路(递加取余判断、环形链表步进
思考:为何递加取余的打印的顺序乍一看好像不是顺序打印,实际上是按顺序交替打印的,怎么优化?可以参考这篇文章的第4节:[13行代码实现两个线程交替打印](https://blog.csdn.net/u010425839/article/details/122502217)******
一、递加取余判断(无锁,存在线程安全问题,在此仅作为一种思路分享)
- 首先定义一个整型变量;
- 每次执行时加一;
- 根据【对2取余后的余数】来决定执行哪个线程任务;
- 执行代码如下:
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();
}
}
二、环形链表步进(无锁,存在线程安全问题,在此仅作为一种思路分享)
- 首先定义一个有两个节点的环形链表,两个节点互为对方的下一节点;
- 每次执行后步进到next下一节点;
- 根据【当前节点是否为想要的节点】来决定执行哪个线程任务;
- 执行代码如下:
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();
}
}