在看毕老师视频时有点困惑 老师说在mian方法中 调用changeFlag()方法会避免线程t1或t2线程出现死循环,但如果一开始就进入t1线程有没有可能就一直循环了~~谢谢各位!
- class StopThread implements Runnable{
- private boolean flag=true;
- public void run(){
- while(flag){
- System.out.println(Thread.currentThread().getName()+"----run");
- }
- }
- public void changeFlag()
- {
- flag=false;
- }
- }
- public class StopThreadDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int num=0;
- StopThread t=new StopThread();
- Thread t1=new Thread(t);
- Thread t2=new Thread(t);
- t1.start();
- t2.start();
- while(true){
- if(num++==60){
- t.changeFlag();
- break;
- }
- System.out.println(Thread.currentThread().getName()+" "+num);
- }
- }
- }
复制代码 |