代码如下
private static Thread mTaskThread = new Thread(new Runnable() {
@Override
public void run() {
count++;
System.out.println("this is time do task:" + count);
}
});
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
mTaskThread.start();
}
}
如上运行程序发现,线程只会执行一次,并会有异常提示。查看Thread源码
/**
* Starts the new Thread of execution. The <code>run()</code> method of
* the receiver will be called by the receiver Thread itself (and not the
* Thread calling <code>start()</code>).
*
* @throws IllegalThreadStateException - if this thread has already started.
* @see Thread#run
*/
public synchronized void start() {
checkNotStarted();
hasBeenStarted = true;
nativeCreate(this, stackSize, daemon);
}
private void checkNotStarted() {
if (hasBeenStarted) {
throw new IllegalThreadStateException("Thread already started");
}
}
可以看出Thread会检查是否执行过,如果已经执行过则会抛出异常。
那么如何使创建的线程可以执行多次呢?
private static void runTask() {
new Thread(new Runnable() {
@Override
public void run() {
count++;
System.out.println("this is time do task:" + count);
}
}).start();
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
runTask();
}
}
这样的操作线程会执行多次,但是每次执行线程对会重新创建线程对象,虽然任务结束后,垃圾回收器会回收对象,但是如果线程执行多次,频繁的创建对象,回收对象会影响运行效率,还有可能因对象来不及回收产生垃圾内存,这样严重影响性能。如何才能够避免可以重复执行线程,而又不影响效率,可以用线程池来执行。
private static ExecutorService mExecutor = Executors.newSingleThreadExecutor();
private static void runTask() {
if (mTaskRunnable == null) {
mTaskRunnable = new Runnable() {
@Override
public void run() {
count++;
System.out.println("this is time do task:" + count);
}
};
}
mExecutor.execute(mTaskRunnable);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
runTask();
}
}
运行显示,多次执行了线程的任务。