我有两个lambda函数(谓词):
final Predicate<Node> isElement = node -> node.getNodeType() == Node.ELEMENT_NODE;
final BiPredicate<Node, String> hasName = (node, name) -> node.getNodeName().equals(name);
Run Code Online (Sandbox Code Playgroud)
我希望以一种简洁的方式组合,如下所示:
// Pseudocode
isElement.and(hasName("tag")) // type of Predicate
Run Code Online (Sandbox Code Playgroud)
然后传递给另一个lambda函数:
final BiFunction<Node, Predicate<Node>, List<Node>> getChilds = (node, cond) -> {
List<Node> resultList = new ArrayList<>();
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); ++i) {
Node tmp = nodeList.item(i);
if (cond.test(tmp)) {
resultList.add(tmp);
}
}
return resultList;
};
Run Code Online (Sandbox Code Playgroud)
结果我期待它看起来像下面这样:
List<Node> listNode = getChilds.apply(document, isElement.and(hasName("tag")));
Run Code Online (Sandbox Code Playgroud)
但是and
方法Predicate …
我正在玩多线程,并且在运行一小段代码时遇到了不一致.以下代码应打印出123123 ...但我得到的是
class RunnableDemo implements Runnable {
private String message;
RunnableDemo(String m) {
message = m;
}
public void run() {
try {
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i));
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestThread {
public static void main(String args[]) throws InterruptedException {
new Thread(new RunnableDemo("1111111")).start();
new Thread(new RunnableDemo("2222222")).start();
new Thread(new RunnableDemo("3333333")).start();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:123231231132123231321
输出:123213123123213213213
输出:123231213213231231213
我没有得到的是它在第一次通过时正确运行(打印'123'),然后第二次通过它打印'231'.如果线程正在打印char,则休眠1秒,然后重复.每次运行代码或至少遵循前3个字符的模式时,模式123123不应该是一致的吗?