如何在不使用destroy()方法的情况下销毁Java中的线程?

时间:2021-11-21 19:52:28

How can I destroy such a thread that perform very long operation?

如何销毁执行非常长时间操作的线程?

I need to solve this problem without setting timeouts for SQL query. I know that Thread.destroy() is deprecated.

我需要解决此问题,而无需为SQL查询设置超时。我知道不推荐使用Thread.destroy()。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Sample {

    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection conn = DriverManager
                            .getConnection("jdbc:mysql://localhost:3306/db");
                    conn.createStatement().execute("SELECT * FROM some_table");
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

}

2 个解决方案

#1


3  

Jon is right, setting timeouts is the correct way to resolve the problem.

Jon是对的,设置超时是解决问题的正确方法。

However, you could have another thread in the background running as a timer which holds a reference to the thread and fires an interrupt. This is effectively a home-grown timeout though!

但是,您可以在后台运行另一个线程作为计时器,该计时器保存对线程的引用并触发中断。这实际上是一个本土超时!

#2


1  

Interrupts are your best choice here.

中断是您最好的选择。

http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

#1


3  

Jon is right, setting timeouts is the correct way to resolve the problem.

Jon是对的,设置超时是解决问题的正确方法。

However, you could have another thread in the background running as a timer which holds a reference to the thread and fires an interrupt. This is effectively a home-grown timeout though!

但是,您可以在后台运行另一个线程作为计时器,该计时器保存对线程的引用并触发中断。这实际上是一个本土超时!

#2


1  

Interrupts are your best choice here.

中断是您最好的选择。

http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html