Java 使用线程是否正确连接
我想执行一个任务,只需要1000毫秒,如果超过,我不想继续执行任务, 我用join来做这个 请告诉我并指导我这是否正确Java 使用线程是否正确连接,java,Java,我想执行一个任务,只需要1000毫秒,如果超过,我不想继续执行任务, 我用join来做这个 请告诉我并指导我这是否正确 import java.util.List; public class MainThread { public static void main(String args[]) throws InterruptedException { Thread mainthread = Thread.currentThread(); ChildT
import java.util.List;
public class MainThread {
public static void main(String args[]) throws InterruptedException {
Thread mainthread = Thread.currentThread();
ChildThread child = new ChildThread();
Thread childThread = new Thread(child);
childThread.start();
mainthread.join(1000);
List list = child.getData();
if(list.size()<0)
{
System.out.println("No Data Found");
}
}
}
中断线程是更常见、更好的方法。如果希望任务最多执行1秒,然后停止,请使用,否则线程将继续运行。需要注意的是,根据实际代码的结构,可能需要传播中断 范例
中断线程是更常见、更好的方法。如果希望任务最多执行1秒,然后停止,请使用,否则线程将继续运行。需要注意的是,根据实际代码的结构,可能需要传播中断 范例
不,这将不起作用,因为此代码将等待一秒钟,如果线程未完成,它将继续运行。线程将继续运行。调用thread.interrupt中断线程,或关闭连接,使其抛出异常并停止线程,然后在线程上进行连接。否,这将不起作用,因为此代码将等待一秒钟,如果线程未完成,它将继续运行。线程将继续运行。调用thread.interrupt中断线程,或关闭连接,使其抛出异常并停止线程,然后在线程上加入。否。不准确的您根本不需要主线程,应该调用childThread.join1000 但是这种方法也有一个问题——它将意味着子线程无论如何都将继续运行。 因此,您还应在连接后调用childThread.interrupt:
childThread.join(1000);
childThread.interrupt();
在子线程中,定期在子线程中执行以下操作:
if (interrupted()) {
return;
}
并在需要的地方处理中断异常-通常是围绕您拥有的任何等待方法。不。不准确的您根本不需要主线程,应该调用childThread.join1000 但是这种方法也有一个问题——它将意味着子线程无论如何都将继续运行。 因此,您还应在连接后调用childThread.interrupt:
childThread.join(1000);
childThread.interrupt();
在子线程中,定期在子线程中执行以下操作:
if (interrupted()) {
return;
}
并在需要的地方处理中断异常-通常围绕您拥有的任何等待方法。是的,就是这样,我看到的唯一问题是在ChildThread列表中,我建议您使用像这样的同步方法,这样您就不会有争用条件
List list = Collections.synchronizedList(new ArrayList());
另外,如果您希望在执行时间超过1000毫秒时停止运行的线程,我建议您使用thread对象的中断方法,并且不要忘记在子线程中捕获中断异常,这样您就不会在日志中出现不必要的异常了,我建议你使用像这样的同步方法,这样你就不会有比赛条件
List list = Collections.synchronizedList(new ArrayList());
另外,如果您希望在执行时间超过1000毫秒时停止正在运行的线程,我建议您使用thread对象的中断方法,不要忘记在子线程中捕获中断异常,这样您就不会在日志中出现不必要的异常