Java中的并发性-仅在方法上?
我在网上读了一些教程,发现很难理解,它们都涉及到建立一个新类和在主服务器上运行线程。我没有main,因为我正在为GUI构建一个后端,而我只是在处理一个接口 我在下面粘贴了一个代码示例,以尝试和演示我想要做的事情Java中的并发性-仅在方法上?,java,multithreading,Java,Multithreading,我在网上读了一些教程,发现很难理解,它们都涉及到建立一个新类和在主服务器上运行线程。我没有main,因为我正在为GUI构建一个后端,而我只是在处理一个接口 我在下面粘贴了一个代码示例,以尝试和演示我想要做的事情 public class TestClass { public void testMethod(){ Queue<List<Long>> q = new ArrayDeque<>(); List<Long> testLis
public class TestClass {
public void testMethod(){
Queue<List<Long>> q = new ArrayDeque<>();
List<Long> testList = new ArrayList<>();
testList.add(9L);
q.add(testList);
while(q.size()>0){
//take off list from front of queue
//manipulate list and return it to queue/Delete it if no more to add and not reached a threshold.
}
公共类TestClass{
公共void testMethod(){
队列q=新的ArrayDeque();
List testList=new ArrayList();
添加测试列表(9L);
q、 添加(测试列表);
而(q.size()>0){
//从队列前面取下起飞名单
//操纵列表并将其返回到队列/删除它(如果没有更多要添加且未达到阈值)。
}
所以基本上我想把while循环作为一个线程来调用,因为我希望能够控制它运行的时间并获得一些效率
有人能给我建议吗
谢谢在循环时更改您的
Thread t = new Thread(){
public void run() {
while (q.size() > 0) {
// take off list from front of queue
// manipulate list and return it to queue/Delete it if no more to
// add and not reached a threshold.
}
//all other code
};
};
t.start();
或者您可以等待线程完成执行,但这会再次阻塞您的testMethod,直到您的while循环完成。我认为这不是您需要的
Thread t = new Thread(){
public void run() {
while (q.size() > 0) {
// take off list from front of queue
// manipulate list and return it to queue/Delete it if no more to
// add and not reached a threshold.
}
};
};
t.start();
t.join();//waits for the thread to finish execution.
//rest of your code.
将while
循环更改为如下内容
Thread t = new Thread(){
public void run() {
while (q.size() > 0) {
// take off list from front of queue
// manipulate list and return it to queue/Delete it if no more to
// add and not reached a threshold.
}
//all other code
};
};
t.start();
或者您可以等待线程完成执行,但这会再次阻塞您的testMethod,直到您的while循环完成。我认为这不是您需要的
Thread t = new Thread(){
public void run() {
while (q.size() > 0) {
// take off list from front of queue
// manipulate list and return it to queue/Delete it if no more to
// add and not reached a threshold.
}
};
};
t.start();
t.join();//waits for the thread to finish execution.
//rest of your code.
这允许我的代码运行@Johnson Charles。然而,while语句后面有代码,我不想在while语句耗尽之前运行。有什么想法吗?你可以将while之后的所有内容移动到线程的run方法,但这取决于你的需要。如果你想只在线程完成其执行后才执行它,请当看到我更新的答案时。是的,这很有效。你知道如何限制运行一定的秒数吗?你必须在时间限制后中断线程,并且在线程中你必须检查中断。比如,在while
循环中,你将检查中断作为if(isInterrupted())抛出新的InterruptedException()
并在run
方法中捕获该异常,方法是将所有内容包装到try catch
。或者,如果您只能等待线程一段时间,请使用join(毫秒等待)
方法,但这不会停止线程的执行。您可以搜索堆栈溢出以中断线程。这允许我的代码运行@Johnson Charles。但是,在while语句之后有代码,我不希望在while语句耗尽之前运行。有什么想法吗?您可以将while语句之后的所有内容移动到线程的运行方法,但这取决于您的需要。如果您希望仅在线程完成其执行后执行它,请查看我的更新答案。是的,这很有效。您知道如何限制运行一定的秒数吗?您必须在时间限制后中断线程,并且在您的线程中必须检查中断例如,在while
循环中,如果(isInterrupted())抛出新的InterruptedException()
并在run
方法中捕获该异常,请将所有内容包装在try catch
中,检查是否有中断。或者如果您只能等待线程一段时间,请使用join(等待毫秒)
方法,但这不会停止线程的执行。您可以在堆栈溢出上搜索是否中断线程。