gpt4 book ai didi

java - 如何通过实现Runnable接口(interface)来减少内存消耗?

转载 作者:行者123 更新时间:2023-12-02 01:54:15 27 4
gpt4 key购买 nike

在实现 Runnable 的类中,为了创建线程,我们实例化 Thread 类并通过传递 Runnable 对象调用声明方法。为了创建两个线程,我们创建了两个 Thread 对象以及 Runnable 对象。但如果类扩展了 Thread 类,我们只为扩展 Thread 类的类创建两个对象。

class ImplementsRunnable implements Runnable {


private int counter = 0;

public void run() {
counter++;
System.out.println("ImplementsRunnable : Counter : " + counter);
}
}

class ExtendsThread extends Thread {

private int counter = 0;

public void run() {
counter++;
System.out.println("ExtendsThread : Counter : " + counter);
}
}

public class ThreadVsRunnable {

public static void main(String args[]) throws Exception {
//Multiple threads share the same object.
ImplementsRunnable rc = new ImplementsRunnable();
Thread t1 = new Thread(rc);
t1.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t2 = new Thread(rc);
t2.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t3 = new Thread(rc);
t3.start();

//Creating new instance for every thread access.
ExtendsThread tc1 = new ExtendsThread();
tc1.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
ExtendsThread tc2 = new ExtendsThread();
tc2.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
ExtendsThread tc3 = new ExtendsThread();
tc3.start();
}
}

最佳答案

注意:实例化 Thread 对象比实例化 Runnable 实例成本更高(资源方面)。通过扩展 Thread 实现 Runnable 背后的想法是线程重用

从概念上讲,线程对象可以(同步)运行任意数量的任务(本例是 runanbles)。例如,执行者可以利用这一点。

Executor executor = Executors.newFixedThreadPool(10);
for(int i = 0; i < 1000; i ++ ) {
executor.execute(() -> System.out.println("test"));
}

在本例中,10 个线程的池运行 1000 个 runanble。与扩展 Thread 相关的开销会增加您必须处理的任务越多(因此,尽管在您的示例中差异很小,但如果您必须运行 10000 个任务,则差异将变得明显)。

因此,实现 Runnable 而不是扩展 Thread 是一个很好的做法。

关于java - 如何通过实现Runnable接口(interface)来减少内存消耗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52529875/

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