死循环里的代码不执行,但是在死循环里加个输出就执行,并且线程也没有退出
package shendi.utils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* -问题 代码原封不动运行,two函数里的死循环感觉像是挂了一样 但是线程没有结束 不执行
* -但是在循环内加个输出,函数就没有问题,Why?
*/
public class Test extends JFrame implements Runnable {
private String type;
private static int i = 0;
public Test() {
JButton button = new JButton("i+1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
i++;
System.out.println("two函数的死循环就是不会被执行 + i现在是:"+i);
}
});
this.add(button);
this.setBounds(10, 10,100,100);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
new Thread(new Test("1")).start();
new Thread(new Test("2")).start();
}
public Test(String type) {this.type = type;}
public static void main(String[] args) {
new Test();
}
private void one() {
while (true) {
// System.out.println(i);
}
}
private void two() {
System.out.println("two被调用了,线程 ");
while (true) {
if (1 == 2) break;
// if (i == 0) System.out.println("i=0 two函数");
if (i > 1) System.out.println("我是活的");
}
System.out.println("two挂了");
}
public void run() {
switch (type) {
case "1":
one();
break;
case "2":
two();
break;
}
}
}