最近在做项目时,发现,线程,不能作为一个类的全局变量。
如果线程做为全局变量时,很容易导致内存溢出,线程最好的使用方法是,创建了线程,立即start();
由于,线程的run方法,不可控性,导致,主程序不知道何时线程跑完了,才可以令内存释放。
//方法一:继承Thread 类,实现run方法。
class ThreadTest extends Thread {
ThreadTest() {
}
public void run() {
// code here ...
}
}
//创建并启动一个线程:
ThreadTest t = new ThreadTest();
t.start();
//方法二:实现 Runnable 接口的类,实现run方法。
class RunTest implements Runnable {
RunTest () {
}
public void run() {
// code here . . .
}
}
//创建并启动一个线程:
RunTest r = new RunTest(143);
new Thread(r).start();