高并发01--银行家算法与线程交替

凡是从时间或者优先级来考虑的都是错的

1、哲学家问题

(1)一次性分配所有筷子

(2)至少一个是左撇子

(3)奇数左撇子,偶数右撇子

package org.example.util;

public class PhilosopherThread extends Thread {

    private Chopsticks left;

    private Chopsticks right;

    private int index;


    public PhilosopherThread(Chopsticks left, Chopsticks right, int index) {
        this.left = left;
        this.index = index;
        this.right = right;
    }

    @Override
    public void run() {

        if (index == 5) {
            synchronized (right) {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(index + "wait left to eat");
                synchronized (right) {
                    System.out.println(index + "get left to eat");
                }
            }
        } else {
            synchronized (left) {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(index + "wait RIGHT to eat");
                synchronized (right) {
                    System.out.println(index + "get RIGHT to eat");
                }
            }
        }

    }

    public static void main(String[] args) {
        Chopsticks chopsticks1 = new Chopsticks();
        Chopsticks chopsticks2 = new Chopsticks();
        Chopsticks chopsticks3 = new Chopsticks();
        Chopsticks chopsticks4 = new Chopsticks();
        Chopsticks chopsticks5 = new Chopsticks();

        PhilosopherThread philosopherThread1 = new PhilosopherThread(chopsticks1, chopsticks2, 1);
        PhilosopherThread philosopherThread2 = new PhilosopherThread(chopsticks2, chopsticks3, 2);
        PhilosopherThread philosopherThread3 = new PhilosopherThread(chopsticks3, chopsticks4, 3);
        PhilosopherThread philosopherThread4 = new PhilosopherThread(chopsticks4, chopsticks5, 4);
        PhilosopherThread philosopherThread5 = new PhilosopherThread(chopsticks5, chopsticks1, 5);
        philosopherThread1.start();
        philosopherThread2.start();
        philosopherThread3.start();
        philosopherThread4.start();
        philosopherThread5.start();

    }
}

 

2、线程交替

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sOz4kXty-1670208286063)(image-20221205092508390.png)]

标识,避免同时死亡

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G6LwJseL-1670208286065)(image-20221205092830810.png)]

一、递加取余判断(无锁)

​ 通过递加求余判断,确保线程交替执行

  1. 首先定义一个整型变量;
  2. 每次执行时加一;
  3. 然后对【取余后的余数】做判断,从而实现线程的交替执行;
  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下一个节点

package org.example.gaobingfa;

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();	
	}
}

三、通过LockSupport锁支持工具类,确保线程1执行后,线程2才执行,中间有阻塞方法park()或者放行方法unpark()

import java.util.concurrent.locks.LockSupport;
public class AlternatePrintOdevity3
{  
	static Thread t1,t2=null;
	static int step = 0;
	public static void task() {
		while(step<10) {
			if(t1 == Thread.currentThread()) {
				System.out.println(t1.getName() + step++);//t1先执行打印
				LockSupport.unpark(t2);//打印后放行t2
				LockSupport.park();//阻塞t1,直到被t2放行
			}else {
				LockSupport.park();//阻塞t2,直到被t1放行
				//能走到这里说明t2已经被t1放行,且目前t1处于阻塞等待方向的状态,接着轮到t2执行打印
				System.out.println(t2.getName() + step++);
				LockSupport.unpark(t1);//打印后放行t1
			}
		}
	}
	public static void main(String[] args) {  
		t1 = new Thread(()->{task();},"#T1#");
		t2 = new Thread(()->{task();},"#T2#");
		t1.start();t2.start();
    }
} 

四、synchronized关键字+Object.wait+Object.notify交替执行,必须有方法在合适的时间主动阻塞和放行

public class AlternatePrintOdevity4
{  
	static Object obj = new Object();
	static int step = 0;
	public static void task() {
		while(step<10) {
			synchronized(obj) {
				System.out.println(Thread.currentThread().getName() + step++);
				obj.notify();
				try {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}
			}
		}
	}
	public static void main(String[] args) {  
		new Thread(()->{task();},"#T1#").start();
		new Thread(()->{task();},"#T2#").start();
    }
}

五、ReentrantLock+conditon.await(阻塞)+condition.signal(放行),与synchronize类似

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
//报错:IllegalMonitorStateException  if the current thread is not the owner of this object's monitor.
//原因:Condition唤醒和阻塞使用的是signal、signalAll和await,注意要和Object的notify、nofityAll和wait区分开
public class AlternatePrintOdevity5
{  
	static ReentrantLock reentrantLock = new ReentrantLock();
	static Condition condition = reentrantLock.newCondition();
	static int step = 0;
	public static void task() {
		while(step<10) {
			reentrantLock.lock();
			System.out.println(Thread.currentThread().getName() + step++);
			condition.signal();
			if(step<=10-1)
				try {condition.await();} catch (InterruptedException e) {e.printStackTrace();}	
			reentrantLock.unlock();
		}
	}
	public static void main(String[] args) {  
		new Thread(()->{task();},"#T1#").start();
		new Thread(()->{task();},"#T2#").start();
    }
}

六、CountDownLatch倒计时计数器门闩(倒计时,主任务执行之前执行的一系列子任务)、CyclicBarrier(屏障,设置屏障点,任务在执行到某个屏障点时停下,等待所有任务都到了才执行下一步)、Semaphore(信号量,多个线程并行执行的许可)

CountDownLatch

import java.util.concurrent.CountDownLatch;
public class AlternatePrintOdevity6
{  
	static CountDownLatch countDownLatch = new CountDownLatch(10);
	public static void task(int remainder) {
		while(countDownLatch.getCount()>0) {//【1】
			if(countDownLatch.getCount()%2==remainder && countDownLatch.getCount()>0) {//【2】
				System.out.println(Thread.currentThread().getName() + (10-countDownLatch.getCount()));
				countDownLatch.countDown();
			}
		}
	}
	public static void main(String[] args) {  
		new Thread(()->{task(0);},"#T1#").start();
		new Thread(()->{task(1);},"#T2#").start();
    }
}

CycliBarrier

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class AlternatePrintOdevity7
{  
	static CyclicBarrier cyclicBarrier = new CyclicBarrier(1);
	static int step = 0;
	public static void task(int remainder) {
		while(step < 10) {
			if(step%2 == remainder) {
				try {cyclicBarrier.await();} catch (InterruptedException | BrokenBarrierException e) {e.printStackTrace();}		
				System.out.println(Thread.currentThread().getName() + step++ );
				cyclicBarrier.reset();
			}			
		}
	}
	public static void main(String[] args) {  
		new Thread(()->{task(0);},"#T1#").start();
		new Thread(()->{task(1);},"#T2#").start();
    }
}

Semaphore

import java.util.concurrent.Semaphore;
public class AlternatePrintOdevity8
{  
	static Semaphore semaphore = new Semaphore(1);
	static int step = 0;
	public static void task(int remainder) {
		while(step < 10) {
			if(step%2 == remainder) {
				try {semaphore.acquire();} catch (InterruptedException e) {e.printStackTrace();}		
				System.out.println(Thread.currentThread().getName() + step++ );
				semaphore.release();
			}			
		}
	}
	public static void main(String[] args) {  
		new Thread(()->{task(0);},"#T1#").start();
		new Thread(()->{task(1);},"#T2#").start();
    }
}


异步线程事务回滚问题
线程终止问题,要么全做要么全不做

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

超级无敌暴龙战士塔塔开

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

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

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

打赏作者

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

抵扣说明:

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

余额充值