Created
January 2, 2024 09:20
-
-
Save chenggangpro/4699c9cd974281b219b3c3363b30470a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.concurrent.TimeUnit; | |
| import java.util.concurrent.atomic.AtomicBoolean; | |
| /** | |
| * @author evans | |
| * @date 2022/3/7 | |
| * @since 1.0.0 | |
| */ | |
| public class PetersonTests { | |
| private static volatile boolean[] flag = new boolean[]{false,false}; | |
| private static volatile int turn = 0; | |
| private static final AtomicBoolean checkFlag = new AtomicBoolean(false); | |
| public void threadX() throws InterruptedException { | |
| while (true) { | |
| flag[0] = true; | |
| turn = 1; | |
| while (flag[1] && turn == 1){ | |
| // System.out.println(Thread.currentThread().getName() + "在等待"); | |
| // TimeUnit.MILLISECONDS.sleep(100); | |
| } | |
| this.execution(); | |
| flag[0] = false; | |
| } | |
| } | |
| public void threadY() throws InterruptedException { | |
| while (true) { | |
| flag[1] = true; | |
| turn = 0; | |
| while (flag[0] && turn == 0){ | |
| // System.out.println(Thread.currentThread().getName() + "在等待"); | |
| // TimeUnit.MILLISECONDS.sleep(100); | |
| } | |
| this.execution(); | |
| flag[1] = false; | |
| } | |
| } | |
| private void execution() throws InterruptedException { | |
| if(checkFlag.compareAndSet(false,true)){ | |
| System.out.println(Thread.currentThread().getName() + "在执行"); | |
| TimeUnit.SECONDS.sleep(1); | |
| if(!checkFlag.compareAndSet(true,false)){ | |
| throw new IllegalStateException("多线程释放,执行标记:"+ checkFlag.get() + ",当前线程:"+ Thread.currentThread().getName()); | |
| } | |
| }else { | |
| throw new IllegalStateException("多线程执行,执行标记:"+ checkFlag.get() + ",当前线程:"+ Thread.currentThread().getName()); | |
| } | |
| } | |
| public static void main(String[] args) throws Exception { | |
| PetersonTests petersonTests = new PetersonTests(); | |
| new Thread(() -> { | |
| try { | |
| petersonTests.threadX(); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| },"X").start(); | |
| new Thread(() -> { | |
| try { | |
| petersonTests.threadY(); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| },"Y").start(); | |
| Thread daemon = new Thread(() -> { | |
| while (true) { | |
| try { | |
| TimeUnit.MILLISECONDS.sleep(100); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| }, "daemon"); | |
| daemon.setDaemon(true); | |
| daemon.start(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment