Preventing cars in a 4-channel connection from an accident in java

I made a Java application for 4-way decoupling. I can move all cars through the intersection using THread.sleep (), but I need to prevent the cars from crashing into each other. (See chart)

alt text

What should i use?

  • Synchronization

  • wait () / notify () / notifyAll ()

  • Threadpanels

  • Canvas (by the way, what is canvas and its purpose? )

I used LayeredPane to place images on top of each other.

Here is my code:

import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JLayeredPane;

import javax.swing.JPanel;

public class Gui {

private JFrame f = new JFrame("Traffic Light");
private JLayeredPane lp = new JLayeredPane();
private JPanel red = new JPanel();
private JPanel car_1 = new JPanel();
private ImageIcon northcar = new ImageIcon("src/north.gif");
private ImageIcon usIcon = new ImageIcon("src/trafficLight.jpg");
private JLabel lb = new JLabel(usIcon);
private JLabel lbcar_1 = new JLabel(northcar);


/*private ImageIcon southcar = new ImageIcon("src/trafficLight.jpg");
private ImageIcon westcar = new ImageIcon("src/trafficLight.jpg");
private ImageIcon eastcar = new ImageIcon("src/trafficLight.jpg");
 */
public Gui() {

    f.setBounds(0, 0, 655, 679);
    f.add(lp);




    car_1.setOpaque(false);
    car_1.setBounds(340, 120, 70, 105);
    //car_1.setBackground(Color.black);
    car_1.add(lbcar_1);




    red.setBounds(0, -5, 650, 650);
    red.add(lb);



    lp.add(red, new Integer(0));
    lp.add(car_1, new Integer(1));


    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    try {
    for (int i = 120; i < 540; i +=1){
            Thread.sleep(10);
            car_1.setBounds(340, i, 70, 105);

        } }catch (Exception e) {
        }


    }

   public static void main(String[] args) {


    Gui frame = new Gui();






   }
   }

Any help is appreciated. Thank you for your time.

Many thanks

+3
source share
2 answers

, 4 , "". , , .

, , ( concurrency ) - . , ( "" ) , , . . .

- , , . , ( , ), . , .

+3

"", - . , .

CountDownLatch.

+1

Source: https://habr.com/ru/post/1750777/


All Articles