[英]How can a Thread constructor can accept a run method directly?
I was refering to DeadLock code and saw this website 我正在参考DeadLock代码,看到了这个网站
http://www.javatpoint.com/deadlock-in-java http://www.javatpoint.com/deadlock-in-java
I saw the java API, but couldn't find any such Thread Constructor and still wondering how is this being compiled in Eclipse IDE ?? 我看到了java API,但找不到任何这样的Thread Constructor,仍然想知道这是如何在Eclipse IDE中编译的?
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
How can a Thread constructor can accept a run method directly? Thread构造函数如何直接接受run方法?
The constructor isn't accepting a run
method (eg, as an argument), that code is creating an anonymous class , see this tutorial . 构造函数不接受
run
方法(例如,作为参数),该代码正在创建匿名类 ,请参阅本教程 。 Behind the scenes, a class with no name (anonymous class) is created that derives from Thread
and overrides the run
method; 在幕后,创建了一个没有名称的类(匿名类),它从
Thread
派生并覆盖run
方法; then an instance of that class is created and assigned to the t1
variable. 然后创建该类的实例并将其分配给
t1
变量。
Just for completeness, though: As of Java 8, it is possible for the Thread
constructor to (in effect) accept a run
function as an argument, because of Java 8's lambda functions. 只是为了完整性,但:从Java 8中, 可以为
Thread
构造函数(实际上)接受run
函数作为参数,因为Java的8位的lambda函数。 That looks like this: 看起来像这样:
Thread t = new Thread(() -> {
System.out.println("Running");
});
This is possible because Thread
has a constructor accepting a Runnable
instance, and Runnable
is a functional interface (an interface that only defines a single function), and so you can create an instance implementing that interface simply by using a lambda and then pass that into the Thread
constructor. 这是可能的,因为
Thread
有一个接受Runnable
实例的构造函数,而Runnable
是一个功能接口 (只定义一个函数的接口),所以你可以简单地使用lambda创建一个实现该接口的实例,然后将其传递给Thread
构造函数。 There's a tutorial on lambdas here . 有一个关于lambda表达式的教程在这里 。 But that's not what the quoted code is doing.
但这并不是引用代码所做的。
Here's the code in your question using a lambda instead of an anonymous class: 这是使用lambda而不是匿名类的问题中的代码:
Thread t1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.