我在Java中使用ExecutorService,我注意到了一个我不理解的行为.我使用Callable,当我调用我的线程(实现Callable的类)时,我设置了一个超时.然后我等待结果,future.get()之后我想检查future.isDone()执行任务期间是否发生超时.
正如我在有关超时的invokeAll文档中所读到的那样: returns a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list. If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have completed.
所以我想我会在两种情况下获得Future结果列表,如果发生超时,如果没有.
现在发生的事情如下:当发生超时时,代码不会继续future.get(),我没有达到可以检查是否发生超时的程度future.isDone().我没有发现任何异常,我直接导致我的代码中的finally块,我真的不明白.
这是我的代码片段:
try {
// start all Threads
results = pool.invokeAll(threads, 3, TimeUnit.SECONDS);
for (Future<String> future : results)
{
try
{ …Run Code Online (Sandbox Code Playgroud) 说我有以下代码:
local t = {};
setmetatable(t, {__call=print});
t(3, 5, 7)
Run Code Online (Sandbox Code Playgroud)
而不是打印:
3 5 7
Run Code Online (Sandbox Code Playgroud)
它打印:
table: 0x9357020 3 5 7
Run Code Online (Sandbox Code Playgroud)
表的id是t.
我怎么能让它像我print直接打电话一样?
我有以下代码
import numpy as np
class Estimator(object):
name = None
def __init__(self):
self.__call__ = self._call
class Mean(Estimator):
name = 'mean'
def _call(self, data):
return np.mean(data)
data = np.arange(10)
Run Code Online (Sandbox Code Playgroud)
现在,为什么我不能将第二类作为第一类的仿函数?
它似乎工作:
M = Mean()
print M.__call__(data) # -> 4.5
Run Code Online (Sandbox Code Playgroud)
M有这样的方法__call__:
print '__call__' in dir(M) # -> True
Run Code Online (Sandbox Code Playgroud)
但它不起作用
print M(data)
Run Code Online (Sandbox Code Playgroud)
我明白了:
TypeError: 'Mean' object is not callable
Run Code Online (Sandbox Code Playgroud) feat_imp = pd.Series(xgbPara.booster().get_fscore()).sort_values(ascending=False)
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)
我可以在pycharm中运行它,但是当我在pyspark中运行它时,会出现类型错误。
谁能告诉我为什么?谢谢?
我是ExecutorService的新手,但我不确定我的方法.对于已知任务,我可以处理多达100个线程.我正在使用下面的通用格式,在那里我创建了FutureTasks列表,然后将它们提交给ExecutorService.ExecutorService返回并将这些挂起的结果添加到另一个列表中.然后我迭代这个列表,在每个挂起的结果上调用get().
我的查询是:直到所有100个线程都完成后,依次不会在每个get()上阻塞吗?有一个更好的方法吗 ?
我是否正确假设get()返回Callable实现的call()方法的结果?我正在使用默认的FutureTask类,并没有将其子类化.
ExecutorService exec = Executors.newFixedThreadPool( NUM_THREADS );
List<JobClass> originalList = new ArrayList<JobClass>();
List<SomeOtherClass> pendingResult = new ArrayList<SomeOtherClass>();
List<Future<SomeOtherClass>> resultList = new ArrayList<Future<SomeOtherClass>>();
for( JobClass sc : originalList )
pendingResult.add( submit( sc );
for( Future<SomeOtherClass> future : futures )
resultList.add( future.get(5, TimeUnit.SECONDS) );
Run Code Online (Sandbox Code Playgroud) 我一直在使用Callable,但现在我需要在该call方法中使用param的函数.我知道这不是一种能力,call我怎么能这样做?
我目前有什么(错误的):
AsyncTask async = new MyAsyncTask();
async.finished(new Callable(param) {
// the function called during async.onPostExecute;
doSomething(param);
});
async.execute(url);
Run Code Online (Sandbox Code Playgroud)
MyAsyncTask:
...
@Override
protected void onPostExecute(JSONObject result) {
//super.onPostExecute(result);
if(result != null) {
try {
this._finished.call(result); // not valid because call accepts no params
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void finished(Callable<Void> func) {
this._finished = func;
}
...
Run Code Online (Sandbox Code Playgroud) 我目前正在编写一个交易游戏,用户连接到服务器,然后互相交易并赚钱等等.但是当我尝试时
if(input.lower() == 'sell'):
sMaterial = raw_input('Material: ')
if(sMaterial.lower() == 'gold'):
sAmount = int(input('Enter amount: '))
if(gold >= sAmount):
mon = mon + (100 * sAmount)
else:
print 'You do not have enough', sMaterial
Run Code Online (Sandbox Code Playgroud)
它抛出错误
> sell
Material: gold
Traceback (most recent call last):
File "Test.py", line 119, in <module>
sAmount = int(input('Enter amount: '))
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)
我使用Linux,Python版本2.7.3,与Geany开发环境.提前致谢.
我有一个代码片段,其中一个循环提交Callable,然后检查这些是否已完成,如果是,则打印出它们的值
ArrayList<Future<ArrayList<String>>> controllList = new ArrayList<Future<ArrayList<String>>>();
System.out.println(""+pagecount);
for(int n=1;n<=pagecount;n++){
if(controllList.size()<10){
Future<ArrayList<String>> temp = exeService.submit(new URLSpider("localhost"));
controllList.add(temp);
}
for(int k=0;k<controllList.size();k++){
if(controllList.get(k).isDone()){
System.out.println("Something done");
ArrayList<String> URLs = controllList.get(k).get();
for(int h=0;h<URLs.size();h++){
System.out.println(URLs.get(h));
}
controllList.remove(k);
}
}
}
Run Code Online (Sandbox Code Playgroud)
URLSpider类:
public class URLSpider implements Callable<ArrayList<String>> {
private TagNode node;
private String pageUrl;
private Object[] links;
private ArrayList<String> detailLinks;
public URLSpider(String completePageURL){
pageUrl = completePageURL;
detailLinks = new ArrayList<String>();
}
@Override
public ArrayList<String> call() throws Exception {
HtmlCleaner cleaner = new HtmlCleaner();
try {
node = …Run Code Online (Sandbox Code Playgroud) 到目前为止,这是我正在做的事情:
# -*- coding: cp1252 -*-
import time
class Item():
def __init__(self, name, description, base_value):
self.name = name
self.description = description
self.ingredients = ingredients
self.base_value = value
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value)
class Metal(Item):
def __init__(self, name, description, ingredients, base_value):
self.smelt_time = smelt_time
self.smelted = smelted
def __str__(self):
return format(self.name, self.description, self.ingredients, self.base_value, self.smelt_time, self.smelted)
class Bronze_Ingot(Metal):
def __init__(self):
self.name = "Bronze Ingot",
self.description = "A refined ingot of bronze."
#self.ingredients = Tin_Ore(1)+Copper_Ore(1) <--- I will get these …Run Code Online (Sandbox Code Playgroud) 我为std :: function设置的目标丢失了,我不知道为什么我可能忽略了这个程序中的一些小错误.有人可以帮忙吗
class Test将lambda注册到单例类,但是当尝试调用回调时,std :: function中的目标集将丢失.
#include <iostream>
#include <functional>
using namespace std;
class callback_store final
{
using callback_func_type = std::function<void()>;
public:
static callback_store instance()
{
static callback_store instance;
return instance;
}
void register_callback(callback_func_type func)
{
std::cout << "register_callback() <<<" << std::endl;
m_func = func;
// I am able to call the targets from here.
std::cout << "register_callback() func() " << std::endl;
func();
std::cout << "register_callback() m_func() " << std::endl;
m_func();
// some stats
std::cout << "register_callback() :: " …Run Code Online (Sandbox Code Playgroud) callable ×10
java ×4
python ×3
android ×1
c++ ×1
c++11 ×1
futuretask ×1
inheritance ×1
lambda ×1
lua ×1
metatable ×1
object ×1
python-2.7 ×1
std-function ×1
string ×1
timeout ×1
tuples ×1
typeerror ×1
xgboost ×1