如何从ExecutorService停止/暂停特定线程?

时间:2016-10-17 04:19:43

标签: java spring multithreading

我有public class locationService extends Service implements OnLocationUpdatedListener, OnActivityUpdatedListener { private LocationGooglePlayServicesProvider provider; NotificationCompat.Builder builder; NotificationManager notificationManager; SmartLocation smartLocation; @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { return super.onUnbind(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { provider = new LocationGooglePlayServicesProvider(); provider.setCheckLocationSettings(true); smartLocation = new SmartLocation.Builder(getApplicationContext()).logging(true).build(); smartLocation.location(provider).continuous().start(this); smartLocation.activity().start(this); return START_NOT_STICKY; } @Override public void onCreate() { super.onCreate(); } @Override public boolean stopService(Intent name) { return super.stopService(name); } @Override public void onDestroy() { stop(); } @Override public void onLocationUpdated(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); } @Override public void onActivityUpdated(DetectedActivity detectedActivity) { } public void stop() { smartLocation.location().stop(); stopForeground(true); } } 方法。并spring scheduler

ExecutorService

每5秒启动我的方法,如果有必要的条件 - 用我的逻辑开始新线程。如何停止/暂停特定线程?

我在veb页面上有按钮,如果我按下它,我需要停止我的线程。

1 个答案:

答案 0 :(得分:0)

关于停止线程,已经有很多关于SO的讨论。出于各种原因,您不应该停止或杀死一个线程,例如:这里注意到:

How do you kill a thread in Java?

为了让线程能够正确地清理它的资源,线程的责任应该是通过以下方式终止自身:定期检查某些条件,例如共享变量或通过线程的中断标志。有关详细信息,请参阅此答案:

How to stop a thread created by implementing runnable interface?