java thread while(true)什么意思

来源:百度知道 编辑:UC知道 时间:2024/05/01 18:35:14
public class Main extends JFrame implements ActionListener, Runnable {

JButton b1 = new JButton("start");
JButton b2 = new JButton("stop");
JPanel p = new JPanel();
TextField tf = new TextField(10);
Thread t;
Date d1;
Date d2;

public Main() {
p.add(b1);
p.add(b2);
p.add(tf);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setContentPane(p);
this.setTitle("计时器");
this.setSize(400, 200);
this.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
}

public void run() {
while (true) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
d2 = new Date();
tf.setText(new Long((d2.getT

java thread while(true)的意思是循环执行某段代码或者方法,示例如下:

while (true) {//死循环,重复执行下列代码
System.out.println("yours code");
Thread.sleep(3000);//睡眠3秒
}

也就是说当程序执行到 while(true){ } 时循环条件永远为真,也就是所说的无限循环。这样用时必须在循环体重定义退出循环的语句,否则程序将陷入死循环!!

这里的true是常量 是布尔类型的
就好比 你输出一句话 System.out.println("hello world!")

"hello world!"就是字符串常量一样
while(true)在这里就是条件成立 进行无限循环的意思