为什么线程停止时java.lang.UnsupportedOperationException?

时间:2014-05-19 06:58:52

标签: android multithreading android-service

我的代码如下:

 public class SimpleService extends Service {
    private MyThread myythread;
    public boolean isRunning = false;
    long interval=30000;
    @Override
    public IBinder onBind(Intent arg0) {
    return null;
    }
    @Override
    public void onCreate() {
    super.onCreate();
    myythread  = new MyThread(interval);
    }
    @Override
    public synchronized void onDestroy() {
    super.onDestroy();
    if(!isRunning){
    myythread.interrupt();
    myythread.stop();
    }
    }
    @Override
    public synchronized void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    if(!isRunning){
    myythread.start();
    isRunning = true;
    }
    }
    class MyThread extends Thread{
    long interval;
    public MyThread(long interval){
    this.interval=interval;
    }
    @Override
    public void run(){
    while(isRunning){
    System.out.println("Service running");
    try {
    fileUpload();
    Thread.sleep(interval);
    } catch (InterruptedException e) {
    isRunning = false;
    e.printStackTrace();
    }
    }
    }
    private void fileUpload() {
    String url=Environment.getExternalStorageDirectory()+"/new_Account.txt";
    if(checkInternetConnection()){
    boolean upload_status=new UploadToFtp().ftpUpload1(url, "new_Account.txt");
    }
    }
    }
    private boolean checkInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
    return true;
    }
    else
    {
    return false;
    }
    }
    }

致电时

@Override
    public synchronized void onDestroy() {
    super.onDestroy();
    if(!isRunning){
    myythread.interrupt();
    myythread.stop();
    }
    }

然后抛出异常:

java.lang.UnsupportedOperationException

如何解决此异常。请帮助我任何人。

4 个答案:

答案 0 :(得分:2)

从JDK8开始,Thread.stop真的不见了。这是第一个被弃用的方法。它现在只抛出UnsupportedOperationException

http://cs.oswego.edu/pipermail/concurrency-interest/2013-December/012028.html http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

答案 1 :(得分:1)

Thread.stop()已弃用。不要使用这种方法。这就是抛出UnsupportedOperationException

见这里:http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

答案 2 :(得分:1)

您可以点击以下链接

请参阅我的解决方案:Why java.lang.UnsupportedOperationException when Thread stop?

使用TimerTask而不是线程的解决方案可以更好地为您的应用程序提供服务并进行更优化。

即使取消也可以。)

P.S:它还有关于为什么停止不适合你的信息。

[参考:] [线程中不支持的操作异常] 2

答案 3 :(得分:0)

我认为你的代码也犯了错误,如果它正在运行,你必须停止它。

@Override
public synchronized void onDestroy() {
super.onDestroy();
if(isRunning){
myythread.interrupt();
myythread.stop();
}
}