我有一个方法,我想打电话.但是,我正在寻找一种干净,简单的方法来杀死它或强迫它返回,如果执行时间太长.
我正在使用Java.
为了显示:
logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
Run Code Online (Sandbox Code Playgroud)
我认为TestExecutor
班级应该implement Callable
继续向这个方向发展.
但我想要做的就是停止,executor.execute()
如果它花了太长时间.
建议...?
编辑
收到的许多建议都假设正在执行的方法需要很长时间才能包含某种循环,并且可以定期检查变量.然而,这种情况并非如此.因此,某些东西不一定是干净的,只会停止执行,这是可以接受的.
我在我的代码中使用Java Callable Future.下面是我使用未来和callables的主要代码 -
public class TimeoutThread {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<String> future = executor.submit(new Task());
try {
System.out.println("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的Task
类,它实现了Callable接口,我需要根据我们拥有的主机名生成URL,然后使用调用SERVERS RestTemplate
.如果第一个主机名中有任何异常,那么我将为另一个主机名生成URL,我将尝试拨打电话.
class Task implements Callable<String> {
private static RestTemplate restTemplate = new RestTemplate();
@Override
public String call() throws Exception {
//.. some code
for(String hostname : hostnames) {
if(hostname == null) {
continue;
}
try …
Run Code Online (Sandbox Code Playgroud) 生成器只是一个函数,它返回一个可以在其上调用的对象,这样每次调用它都会返回一些值,直到它引发一个StopIteration异常,表示已生成所有值.这样的对象称为迭代器.
>>> def myGen(n):
... yield n
... yield n + 1
...
>>> g = myGen(6)
Run Code Online (Sandbox Code Playgroud)
我从Python中理解生成器中引用了这个?
这是我想弄清楚的:
哪个是发电机?myGen
还是myGen(6)
?
根据上面提到的报价,我认为发电机应该是myGen
.并且myGen(6)
是返回的迭代器对象.但我真的不确定.
当我尝试这个时:
>>> type(myGen)
<type 'function'>
>>> type(g) # <1>this is confusing me.
<type 'generator'>
>>> callable(g) # <2> g is not callable.
False
>>> callable(myGen)
True
>>> g is iter(g) # <3> so g should an iterable and an iterator
True # at the same time. And it …
Run Code Online (Sandbox Code Playgroud)我想动态分配一个函数实现.
让我们从以下开始:
class Doer(object):
def __init__(self):
self.name = "Bob"
def doSomething(self):
print "%s got it done" % self.name
def doItBetter(self):
print "Done better"
Run Code Online (Sandbox Code Playgroud)
在其他语言中,我们将使doItBetter成为匿名函数并将其分配给对象.但是不支持Python中的匿名函数.相反,我们将尝试创建一个可调用的类实例,并将其分配给该类:
class Doer(object):
def __init__(self):
self.name = "Bob"
class DoItBetter(object):
def __call__(self):
print "%s got it done better" % self.name
Doer.doSomething = DoItBetter()
doer = Doer()
doer.doSomething()
Run Code Online (Sandbox Code Playgroud)
这给了我这个:
回溯(最近一次调用最后一次):第13行,在doer.doSomething()第9行,在调用 打印"%s让它做得更好"%self.name AttributeError:'DoItBetter'对象没有属性'name'
最后,我尝试将callable作为属性分配给对象实例并调用它:
class Doer(object):
def __init__(self):
self.name = "Bob"
class DoItBetter(object):
def __call__(self):
print "%s got it done better" % self.name
doer = Doer()
doer.doSomething = …
Run Code Online (Sandbox Code Playgroud) 我正在创建一个基本程序,它将使用GUI来获取商品的价格,如果初始价格低于10,则从价格中扣除10%,或者如果初始价格是,则从价格中取20%的折扣大于十:
import easygui
price=easygui.enterbox("What is the price of the item?")
if float(price) < 10:
easygui.msgbox("Your new price is: $"(float(price) * 0.1))
elif float(price) > 10:
easygui.msgbox("Your new price is: $"(float(price) * 0.2))
Run Code Online (Sandbox Code Playgroud)
我不断收到此错误:
easygui.msgbox("Your new price is: $"(float(price) * 0.1))
TypeError: 'str' object is not callable`
Run Code Online (Sandbox Code Playgroud)
为什么我收到此错误?
我查看了这个帖子,但有些概念高于我目前的水平.在Python 2.x中,callable()
内置方法存在; 是否有一种简单的方法来检查是否可以使用Python 3调用某些内容?
如何在JavaScript中为可调用对象创建构造函数?
我尝试了各种各样的方式,比如跟随.这个例子只是缩短了实际对象的例子.
function CallablePoint(x, y) {
function point() {
// Complex calculations at this point
return point
}
point.x = x
point.y = y
return point
}
Run Code Online (Sandbox Code Playgroud)
这工作在第一,但它创建的对象不是实例CallablePoint
,因此它不会从复制的属性CallablePoint.prototype
,并说false
上instanceof CallablePoint
.是否可以为可调用对象创建工作构造函数?
我刚学习新的java8功能.这是我的问题:
为什么不允许将Callable<Void>
其用作lambda表达式的功能接口?(编译器抱怨返回值)并且在Callable<Integer>
那里使用它仍然是完全合法的.以下是示例代码:
public class Test {
public static void main(String[] args) throws Exception {
// works fine
testInt(() -> {
System.out.println("From testInt method");
return 1;
});
testVoid(() -> {
System.out.println("From testVoid method");
// error! can't return void?
});
}
public static void testInt(Callable<Integer> callable) throws Exception {
callable.call();
}
public static void testVoid(Callable<Void> callable) throws Exception {
callable.call();
}
}
Run Code Online (Sandbox Code Playgroud)
如何解释这种行为?
为什么我的单元测试在调试模式下成功但在正常运行时失败?
public class ExecutorServiceTest extends MockitoTestCase{
private int numThreads;
private ExecutorService pool;
private volatile boolean interruptedBitSet;
@Override
public void setUp() {
numThreads = 5;
pool = Executors.newFixedThreadPool(numThreads);
}
class TaskChecksForInterruptedBit implements Callable<String> {
@Override
public String call() throws Exception {
interruptedBitSet = false;
while (!Thread.currentThread().isInterrupted()) {
}
interruptedBitSet = Thread.currentThread().isInterrupted();
return "blah";
}
}
public void testCancelSetsInterruptedBitInCallable() throws Exception {
interruptedBitSet = false;
final Future<String> future =
pool.submit(new TaskChecksForInterruptedBit());
final boolean wasJustCancelled = future.cancel(true);
assertTrue(wasJustCancelled);
// Give time for the …
Run Code Online (Sandbox Code Playgroud) callable ×10
java ×4
python ×4
comparison ×1
concurrency ×1
constructor ×1
future ×1
generator ×1
java-8 ×1
javascript ×1
junit ×1
lambda ×1
python-3.x ×1
resttemplate ×1
string ×1
void ×1