Aero Aero - 3 months ago 18
Java Question

Intellij IDEA threading issue

I have a problem with IDEA 2016.2.2

I wrote a threading demo with flying ball


import javax.swing.*;
import java.awt.*;

public class Ball extends JFrame implements Runnable{
private DrawPanel drawPanel = new DrawPanel();
private int b_x; // ball's x
private int b_y; // ball's y
private int b_d; // ball's diameter
private Thread thread = null;
private JButton button;
private boolean flag = false;

private Ball(){
initGUI();
b_x = b_y = b_d = 50;
thread = new Thread(this);
thread.start();
}

private void initGUI(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Ball Thread Demo");
this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout());
this.add(drawPanel, BorderLayout.CENTER);

button = new JButton("Start");
this.add(button, BorderLayout.NORTH);

button.addActionListener(e -> {
button.setText(flag ? "Start" : "Stop");
flag = !flag;
});
}

@Override
public void run() {
while(true){
//System.out.println();
if(flag) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
b_x += 1;
b_y += 1;
drawPanel.repaint();
}
}
}

class DrawPanel extends JPanel{
@Override
protected void paintBorder(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}

@Override
protected void paintChildren(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(247, 123, 40));
g2d.fillOval(b_x, b_y, b_d, b_d);
}
}

public static void main(String[] args){
new Ball().setVisible(true);
}
}


So, the problem is - if I launch this code via cmd - it works good.
But in IDEA it works only with
System.out.println
that comment out in
run
method, another way nothing is happened. Is that an issue of this IDE or I am missing smth important?

Meo Meo
Answer

b_x, b_y and flag need to be made volatile, since they are updated and read in different threads.

Comments