例如,我有一个名为A的类.我可以使一个对象可以调用,就像Python一样吗?例如 :
def myObject = new A()
myObject()
Run Code Online (Sandbox Code Playgroud)
那会调用一些对象方法.可以吗?
我不确定这是否是调用函数的最佳方法before和after函数f1().
class ba(object):
def __init__(self, call, before, after):
self.call = call
self.before = before
self.after = after
def __call__(self, *args):
self.before()
r = self.call(*args)
self.after()
return r
class test1(object):
def mybefore(self):
print "before func call"
def myafter(self):
print "after func call"
def meth1(a1, a2):
print "meth1(a1=%d, a2=%d)" % (a1, a2)
t = test1()
wmeth1 = ba(meth1, t.mybefore, t.myafter)
wmeth1(1, 2)
Run Code Online (Sandbox Code Playgroud)
请指教.
这是我最近遇到的一个问题.谷歌似乎没有答案所以我把它带给堆栈溢出的好人.
我正在寻找一种使用函数输出填充列表的简单方法.像这样的东西:
fill(random.random(), 3) #=> [0.04095623, 0.39761869, 0.46227642]
Run Code Online (Sandbox Code Playgroud)
以下是我发现的其他方法.但我对它们并不满意,因为它们看起来效率低下.
results = []
for x in xrange(3): results.append(random.random())
#results => [0.04095623, 0.39761869, 0.46227642]
Run Code Online (Sandbox Code Playgroud)
和
map(lambda x: random.random(), [None] * 3)
#=> [0.04095623, 0.39761869, 0.46227642]
Run Code Online (Sandbox Code Playgroud)
建议?
感谢所有的答案.我知道有一种更蟒蛇式的方式.
对效率问题......
$ python --version
Python 2.7.1+
$ python -m timeit "import random" "map(lambda x: random.random(), [None] * 3)"
1000000 loops, best of 3: 1.65 usec per loop
$ python -m timeit "import random" "results = []" "for x in xrange(3): results.append(random.random())"
1000000 loops, best of …Run Code Online (Sandbox Code Playgroud) 我正在尝试更改报告的执行并将其以并发方式完成.在'serail模式'中,执行测试需要30秒,当使用并发模式时,我得到27秒(考虑到连续几步必须采取结果).
我仍然没有得到的是这一行:
ExecutorService executor = Executors.newFixedThreadPool(4);
Run Code Online (Sandbox Code Playgroud)
我的计算机装有2x2.6 Ghz四核,如果newFixedThreadPool为高(16),我希望执行时间会减少.实际上,我增加newFixedThreadPool越多,执行速度越慢.这引出了一个问题:我做错了什么或者我没理解什么?!?!
我从我的执行中嵌入了2个结果截图.
A. newSingleThreadExecuter - 在23秒内运行
B. newFixedThreadPool(4) - 在43秒内运行.
每次我提交一个'Worker'我得到system.out currentTimeMillis和'fatched tkt'结果是从db获取数据所需的毫秒数.(在策略A中 - 它需要约3毫秒,而在B中最多需要7毫秒).
Stopper stopper = new Stopper();
for (Long iNum : multimap.asMap().keySet())
{
List<Long> tickets = (List<Long>) multimap.get(iNum);
for (Long ticketNumber : tickets)
{
pojoPks = getPkData(iNum);
Callable<PojoTicket> worker = new MaxCommThread(ticketNumber, pojoPks);
Future<PojoTicket> submit = executor.submit(worker);
futures.add(submit);
}
}
System.out.println("futurues: " +futures.size());
for (Future<PojoTicket> future : futures)
{
try
{
PojoTicket pojoTicket = future.get();
//do the rest here
} …Run Code Online (Sandbox Code Playgroud) java concurrency multithreading callable java.util.concurrent
这是一个脑力激荡者.
我知道这个实际代码在很多层面都很糟糕.我的问题不是如何做到这一点(我知道静态初始化块),但为什么这不起作用,为了我理解Java序列化的好处.
为什么这样做
import java.io.*;
import java.util.*;
class Main {
static Comparator<String> COMPARE_STRING_LENGTH;
static {
class CompareStringReverse implements Comparator<String>, Serializable {
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
COMPARE_STRING_LENGTH = new CompareStringReverse();
}
public static void main(String[] args) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.ser"));
out.writeObject(new TreeSet<String>(COMPARE_STRING_LENGTH));
out.close();
}
}
Run Code Online (Sandbox Code Playgroud)
而这个
import java.io.*;
import java.util.*;
import java.util.concurrent.Callable;
class Main {
static Comparator<String> COMPARE_STRING_LENGTH = new Callable<Comparator<String>>() {
public …Run Code Online (Sandbox Code Playgroud) 我试图在下面的实现中模仿 php 的内置 usort 函数定义:
class heapSort {
static function hsort(array &$array, callable $cmp_function){
// logic
}
}
class utility{
static function mycomparator(){
// logic
}
}
$array = array(5,3,8,1);
$callback = array('utility','mycomparator');
heapSort::hsort($array, $callback);
Run Code Online (Sandbox Code Playgroud)
虽然变量$callback是“可调用的”,但为什么我会遇到致命错误?
传递给 heapSort::hsort() 的参数 2 必须是 callable 的实例。
更具体地说,我如何制作/类型转换$variable为可调用的?
我正在开发一个项目,其中我有多个接口和两个实现类,需要实现这两个接口.
假设我的第一个接口是 -
public Interface interfaceA {
public String abc() throws Exception;
}
Run Code Online (Sandbox Code Playgroud)
它的实施是 -
public class TestA implements interfaceA {
// abc method
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它 -
TestA testA = new TestA();
testA.abc();
Run Code Online (Sandbox Code Playgroud)
现在我的第二个界面是 -
public Interface interfaceB {
public String xyz() throws Exception;
}
Run Code Online (Sandbox Code Playgroud)
它的实施是 -
public class TestB implements interfaceB {
// xyz method
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它 -
TestB testB = new TestB();
testB.xyz();
Run Code Online (Sandbox Code Playgroud)
问题陈述:-
现在我的问题是 - 有什么办法,我可以并行执行这两个实现类吗?我不想按顺序运行它.
意思是,我想并行运行TestA和TestB实现?这可能吗?
java parallel-processing multithreading callable executorservice
我试图通过可调用对象调用类的构造函数,因此我有以下代码:
$callable = array('Foo', '__construct');
Run Code Online (Sandbox Code Playgroud)
但是调用此方法会引发以下错误:
Fatal error: Non-static method Foo::__construct() cannot be called statically
Run Code Online (Sandbox Code Playgroud)
我知道构造函数不是静态方法,但我不能使用现有实例来调用新实例的构造函数(因为它只会再次调用现有对象上的构造函数),有什么方法可以像这样调用构造函数?
我不能为我的生活找到以下的解释:
public static void takesAFunction(Function<String, Void> func) {
func.apply("Hi I'm running a function");
}
public static void takesAConsumer(Consumer<String> func) {
func.accept("Hi I'm running a consumer");
}
public static void main(String[] args) throws Exception {
takesAFunction((String str) -> { System.out.println(str); });
takesAConsumer((String str) -> { System.out.println(str); });
}
Run Code Online (Sandbox Code Playgroud)
我正在使用JDK 1.8.0_66和该行
takesAFunction((String str) -> { System.out.println(str); });
Run Code Online (Sandbox Code Playgroud)
被标记为错误
The method takesAFunction(Function<String,Void>) in the type MyClass
is not applicable for the arguments ((String str) -> {})
Run Code Online (Sandbox Code Playgroud)
我不明白是怎么回事
Function<String, Void>
Run Code Online (Sandbox Code Playgroud)
不同于
Consumer<String>
Run Code Online (Sandbox Code Playgroud)
当两者都不返回并且都接受单个String参数时.
有人可以解释一下它是否会被杀死. …
我有一个实现可调用接口的类.我想使用ScheduledExecutorService接口的scheduleAtFixedRate方法为该类安排任务.但是,scheduleAtFixedRate需要一个可运行的对象作为它可以调度的命令.
因此我需要一些方法可以将callable转换为runnable.我试过简单的铸造,但那是行不通的.
示例代码:
package org.study.threading.executorDemo;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class ScheduledExecutionTest implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("inside the call method");
return null;
}
}
public class ScheduledExecution {
public static void main(String[] args) {
ScheduledExecutorService sec = Executors.newScheduledThreadPool(10);
sec.scheduleAtFixedRate(new ScheduledExecutionTest(), 5, 2, TimeUnit.SECONDS);
}
}
Run Code Online (Sandbox Code Playgroud) java multithreading callable runnable scheduledexecutorservice