[英]Create object from implement Runnable interface in threading - Java
I'm new in Java and threading.我是 Java 和线程的新手。
Is there any different to create an runnable object as Runnable
and ThreadState
:将可运行对象创建为
Runnable
和ThreadState
有什么不同:
class ThreadState implements Runnable {
public void run() {
System.out.println("xxxxx");
}
public static void main(String args[]) {
Runnable r1 = new ThreadState();
Thread t1 = new Thread(r1);
t1.start();
}
}
And和
class ThreadState implements Runnable {
public void run() {
System.out.println("xxxxx");
}
public static void main(String args[]) {
ThreadState r1 = new ThreadState();
Thread t1 = new Thread(r1);
t1.start();
}
}
Thanks!谢谢!
In your code, r1
is neither a Runnable
nor a ThreadState
.在您的代码中,
r1
既不是Runnable
也不是ThreadState
。
It is just a reference to an object of that type.它只是对该类型对象的引用。
In both cases, with the execution of new ThreadState()
you create an instance of ThreadState
that is also an instance of Runnable
.在这两种情况下,通过执行
new ThreadState()
您创建了一个ThreadState
实例,它也是Runnable
的一个实例。
As a result, your code snippets are equivalent.因此,您的代码片段是等效的。
public class ThreadState implements Runnable
{
@Override
public final void run()
{
System.out.println( "xxxxx" );
}
public static final void main( String... args )
{
Runnable r1 = new ThreadState();
if( r1 instanceof ThreadState ) System.out.println( "r1 is ThreadState" ); // will be printed
Thread t1 = new Thread( r1 );
t1.start();
}
}
vs.对比
public class ThreadState implements Runnable
{
@Override
public final void run()
{
System.out.println( "xxxxx" );
}
public static final void main( String... args[] )
{
ThreadState r1 = new ThreadState();
if( r1 instanceof Runnable ) System.out.println( "r1 is Runnable" ); // will be printed
Thread t1 = new Thread( r1 );
t1.start();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.