首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

请教一个释放内存的有关问题

2011-12-08 
请教一个释放内存的问题小弟在学习Thinkinginjava时,看到如下一个例子://:c14:Interrupt.java//FromThinki

请教一个释放内存的问题
小弟在学习Thinking   in   java时,看到如下一个例子:

//:   c14:Interrupt.java
//   From   'Thinking   in   Java,   2nd   ed. '   by   Bruce   Eckel
//   www.BruceEckel.com.   See   copyright   notice   in   CopyRight.txt.
//   The   alternative   approach   to   using  
//   stop()   when   a   thread   is   blocked.
//   <applet   code=Interrupt   width=200   height=100>
//   </applet>
import   javax.swing.*;
import   java.awt.*;
import   java.awt.event.*;
import   com.bruceeckel.swing.*;

class   Blocked   extends   Thread   {
    public   synchronized   void   run()   {
        try   {
            wait();   //   Blocks
        }   catch(InterruptedException   e)   {
            System.err.println( "Interrupted ");
        }
        System.out.println( "Exiting   run() ");
    }
}

public   class   Interrupt   extends   JApplet   {
    private   JButton  
        interrupt   =   new   JButton( "Interrupt ");
    private   Blocked   blocked   =   new   Blocked();
    public   void   init()   {
        Container   cp   =   getContentPane();
        cp.setLayout(new   FlowLayout());
        cp.add(interrupt);
        interrupt.addActionListener(
            new   ActionListener()   {
                public  
                void   actionPerformed(ActionEvent   e)   {
                    System.out.println( "Button   pressed ");
                    if(blocked   ==   null)   return;
                    /**   不明白的地方开始   */
                    Thread   remove   =   blocked;
                    blocked   =   null;   //   to   release   it
                    remove.interrupt();
                    /**   不明白的地方结束   */
                }
            });
        blocked.start();
    }
    public   static   void   main(String[]   args)   {
        Console.run(new   Interrupt(),   200,   100);
    }
}   ///:~


小弟这个地方不太明白,remove指向block原来的那块内存区域后,那块内存也不会得到释放啊~和直接调用方法
block.interrupt();
有什么区别呢?请高人指点!多谢

[解决办法]
if(blocked == null) return;有这句话,使 blocked = null;就是为了防止按钮被多次点击。remove.interrupt(); block.interrupt(); 没区别。



[解决办法]
remove指向block原来的那块内存区域后,那块内存也不会得到释放啊
============================================================
因为后面接着blocked = null
当执行完remove.interrupt();后,remove也不指向block原来的那块内存区域了,
所以JVM机会在合适的时候释放block原来的那块内存区域。

和直接调用方法
block.interrupt(); 有什么区别呢?
================================
没有区别

Thread remove = blocked;
blocked = null; // to release it
remove.interrupt();
=======================
可以改成:
blocked.interrupt();
blocked=null;

结果一样

热点排行