There are multiple threads, representing the running car, write a traffic light function, pause all car threads when the red light is on, and start all threads when the green light is on.

Aug.07,2021

is this the topic of a tutoring organization? when you learn multithreading for traffic lights, you often see in the materials that you can directly use Baidu multithreaded traffic lights. There should be many examples, which may be more complete than your consideration of this topic. You can delete some of the logic in their code and it will be what you want.


refer to CountDownLatch and simply implement it. The principle is nothing more than AQS .

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 
 * 
 * @author ccr at 20181008
 */
public class TrafficLightLatch {
    private final class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected int tryAcquireShared(int ignored) {
            return redLight == 0 ? 1 : -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            return true;
        }
    }

    /**
     * 00
     */
    volatile private int redLight;

    private Sync sync;

    /**
     * 
     * @param redLight 00
     */
    public TrafficLightLatch(int redLight) {
        this.redLight = redLight;
        sync = new Sync();
    }

    /**
     * 
     * @throws InterruptedException
     */
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    /**
     * 
     */
    public void switchRed(){
        this.redLight = 1;
    }

    /**
     * 
     */
    public void switchGreen() {
        this.redLight = 0;
        sync.releaseShared(0);
    }

    /**
     * 
     */
    public boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
     * 
     * @return Collection
     */
    public Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    public String getLightColor() {
        return redLight == 0 ? "" : "";
    }

    //
    public static void main(String[] args) throws IOException, InterruptedException {
        //
        TrafficLightLatch light = new TrafficLightLatch(1);
        List<Thread> threads = new ArrayList<>();
        //10
        for (int i = 0; i < 10; iPP) {
            Thread thread = new Thread(() -> {
                while (!Thread.currentThread().isInterrupted()) {
                    //System.out.println(String.format("%s: -%s",Thread.currentThread().getName(),light.getLightColor()));
                    try {
                        //
                        light.await();
                    } catch (InterruptedException e) {
                        //
                        Thread.currentThread().interrupt();
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        //
                        Thread.currentThread().interrupt();
                    }
                    System.out.println(String.format("%s: -%s ",Thread.currentThread().getName(),light.getLightColor()));
                }
            });
            threads.add(thread);
            thread.start();
        }

        //
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String command;
        while ((command = reader.readLine()) != null) {
            if(command.equals("switchRed")) {
                light.switchRed();
                Thread.sleep(1000);
                System.out.println(String.format(":%d",light.getQueuedThreads().size()));
            } else if(command.equals("switchGreen")) {
                light.switchGreen();
                Thread.sleep(500);
                System.out.println(String.format(":%d",light.getQueuedThreads().size()));
            } else if (command.equals("stop")){
                System.out.println("terminating...");
                threads.forEach(Thread::interrupt);
                break;
            }
        }
    }
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b36838-2c004.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b36838-2c004.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?