gpt4 book ai didi

java - Intellij IDEA 线程问题

转载 作者:行者123 更新时间:2023-11-30 07:10:36 24 4
gpt4 key购买 nike

我的 IDEA 2016.2.2 有问题
我用飞球写了一个线程演示

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

所以,问题是 - 如果我通过 cmd 启动此代码 - 它工作得很好。但在 IDEA 中,它只能与在 run 方法中注释掉的 System.out.println 一起使用,另一种方式什么也没有发生。这是这个 IDE 的问题还是我错过了一些重要的事情?

最佳答案

b_xb_yflag 需要设为 volatile ,因为它们以不同的方式更新和读取线程。

关于java - Intellij IDEA 线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com