qq_25611195
qq_25611195
采纳率100%
2016-12-03 15:17

java 多线程run函数 while循环内如果像此程序那样注释掉 会无法实现功能()

2
已采纳

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Lottery extends JFrame {
public JLabel jb = new JLabel("haha");
public JButton jbt = new JButton("start");
boolean bool1 = false;

public Lottery() {
    this.setVisible(true);
    this.setSize(500, 300);
    this.setTitle("Lottery");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLayout(null);
    jb.setBounds(50, 20, 200, 30);
    jbt.setBounds(50, 60, 140, 30);
    jbt.addActionListener(new BtListener());
    this.add(jb);
    this.add(jbt);
    Caipiao_thread c = new Caipiao_thread();
    Thread t = new Thread(c);
    t.start();

}

public static void main(String[] args) {

    new Lottery();
}

public static int[] create_number() {
    int[] number = new int[6];
    int i = 0;

    int one;
    while (i < 6) {
        boolean bool = true;// 放在循环内!!!!!!!!
        if (i == 0) {
            number[i] = (int) (Math.random() * 36 + 1);
            i++;
        } else {
            one = (int) (Math.random() * 36 + 1);
            for (int j = 0; j < i; j++) {
                if (number[j] == one) {
                    bool = false;
                    break;
                }
            }
            if (bool) {
                number[i] = one;
                i++;
            }
        }
    }
    return number;

}

class BtListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if (jbt.getText() == "start") {
            jbt.setText("stop");
            bool1 = true;
        } else if (jbt.getText() == "stop") {
            jbt.setText("start");
            bool1 = false;
        }
    }

}

class Caipiao_thread implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            //system.out.println();
            while (bool1) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                int[] number = create_number();

                String s = "";
                for (int i = 0; i < number.length; i++) {
                    s = s + number[i] + "  ";
                }

                jb.setText(s);
            }
        }
    }
}

}
在同学电脑上测试是不可以的,我自己的电脑无论加不加system.out.println();都可以
跟IDE或者jdk有关吗?谢谢各位

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • conansix 看山 5年前

    这个应该是与swing线程抢占有关,只要在Caipiao_thread这个的while(true)里面加一个Thread.sleep就能够显示,或者将对JLabel对象的修改放在主线程里面。

    点赞 评论 复制链接分享
  • devmiao devmiao 5年前