开启Thread线程只执行一次

代码如下

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();
	}
}

运行显示,多次执行了线程的任务。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值