gpt4 book ai didi

java - 为什么要在新的Thread中写新的Runnable呢?

转载 作者:行者123 更新时间:2023-12-01 21:41:18 25 4
gpt4 key购买 nike

谁能解释一下为什么要在新线程中写入新的 Runnable 吗?我第一次在 android 开发者那里看到这个,请参阅下面链接中的代码。另外,你能告诉我们为什么我们需要在单独的线程中实现通知吗?

http://developer.android.com/training/notify-user/display-progress.html

我曾经通过 new Thread 或 Runnable 创建线程,但不是一起创建,所以有点困惑..

最佳答案

我们可以通过两种方式创建线程

by extending Thread class and by implementing Runnable interface

如果我们通过扩展 Thread 类来创建一个类,如下所示

class ThreadDemo extends Thread{
public void run(){
//job of a thread
}
public static void main (String[] args){
ThreadDemo d = new ThreadDemo();
d.start();
}
}

您可以直接调用start()jvm内部调用run()方法,以便您可以在 run() 中定义 Thread 的作业通过在你的类(class)中覆盖它。但是如果你通过实现 Runnable(I) 创建线程像下面这样。

class ThreadDemo implements Runnable{
public void run(){
//job of Thread
}
public static void main(String[] args){
ThreadDemo d = new ThreadDemo(); //d.start() is not possible
Thread t = new Thread(d);//where d is target runnable
t.start()
}
}

你不能打电话start()直接与 ThreadDemo实例因为Runnable(I)仅包含run()方法,所以你必须传递你的 ThreadDemo实例为Thread Thread时的实例创建它会初始化您的 target Runnable instance并调用Runnable run()方法不Threadrun()方法。

new Thread(
new Runnable() {
......
.....
}
}
).start();

类似于

ThreadDemo d = new ThreadDemo(); //d.start() is not possible
Thread t = new Thread(d);//where d is target runnable
t.start()

关于java - 为什么要在新的Thread中写新的Runnable呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com