本帖最后由 孙百鑫 于 2013-6-27 07:52 编辑
- 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;
- }
- }
- class Demo
- {
- public static void main(String[] args)
- {
- StopThread st = new StopThread();
- Thread t1 = new Thread(st);
- Thread t2 = new Thread(st);
- t1.start();
- t2.start();
- int num = 0;
- while(true)
- {
- if(num++ == 10)
- {
- st.changeFlag();
- break;
- }
- System.out.println(Thread.currentThread().getName()+"......."+num);
- }
- System.out.println("over");
- }
- }
复制代码 打印结果是
Thread-1....run
Thread-1....run
main.......6
main.......7
main.......8
main.......9
main.......10
over
Thread-1....run
Thread-0....run
请按任意键继续. . .
不是打印over都结束了吗?为什么每次运行最后都有他们两条语句打印? |