一个 CPU 一次可以运行多少个线程

2022-09-04 00:46:07

我想知道单个应用程序的CPU可以同时运行多少个线程?

我同样简单::

import java.awt.SystemColor;
import java.util.Date;

public class Threadcall {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("--------------------------");
        System.out.println(Runtime.getRuntime().availableProcessors());
        System.out.println("--------------------------");
        for (int i = 0; i < 5; i++) {
            new samplethread(i);
        }
        // create a new thread
        //samplethread1.run();
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println("Main Thread: " + i + "\t" + new Date());
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }
        System.out.println("Main thread exiting.");
    }
}

public class samplethread implements Runnable {

    Thread t;

    samplethread(int i) {
        // Create a new, second thread
        t = new Thread(this, Integer.toString(i));
        System.out.println("Child thread Creation NO: " + i + "\t" + t.getName());



        t.start(); // Start the thread
        // t.run();

    }

    @Override
    public void run() {

        try {
            for (int i = 5; i > 0; i--) {

                System.out.println("Child Thread Run: " + i + "\t" + t.getName() + "\t" + new Date());
                // Let the thread sleep for a while.
                System.out.println("****************************");
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            System.out.println("Child interrupted.");
        }
        System.out.println("Exiting child thread.");
    }
}

它显示的输出如下:

处理器编号: 2

主线: 3 星期日 5月 26 19:23:19 IST 2013

子线程运行: 1 2 2 周日 5 月 26 19:23:19 IST 2013

子线程运行: 1 1 1 星期日 五月 26 19:23:19 IST 2013

子线程运行: 1 3 星期日 5 月 26 19:23:19 IST 2013

子线程运行: 1 0 星期日 五月 26 19:23:19 IST 2013

子线程运行: 1 4 星期日 五月 26 19:23:19 IST 2013

从输出中我们可以看到,在同一时刻可以执行五个线程(我甚至在几毫秒内打印结果)..........我有两个处理器,在程序中报告。

这怎么可能?

因为一个线程一次只能在一个 CPU 中运行,但它表明五个线程同时运行。

有没有办法证明只有一个线程可以同时在一个CPU中运行......

如果我修改我的代码,比如:

t.start();
t.join();

然后它显示输出如下:

子线程创建 NO: 99 99 子线程运行: 5 99 星期日 5月 26 21:02:32 IST 2013

子线程运行: 4 99 星期日 5 月 26 21:02:32 IST 2013

子线程运行: 3 99 星期日 五月 26 21:02:33 IST 2013

子线程运行: 2 99 星期日 五月 26 21:02:33 IST 2013

子线程运行: 1 99 星期日 五月 26 21:02:34 IST 2013

那么,如果我在代码中添加一个简单的行,那么它怎么可能显示只有两个线程可以访问两个处理器呢?


答案 1

这取决于你所说的“同时”是什么意思。您可以通过切换在同一处理器上执行无限数量的线程,即从一个线程执行一行代码,然后切换到另一个线程,执行一行代码,然后切换回来。处理器通过非常快速地来回切换来模仿“同时执行”。

但是,大多数处理器在它们可以执行的真正并发线程数上受到限制,因为它们具有内核数,但由于共享资源和硬件,即使这样也是一个糟糕的估计。从理论上讲,您可以在4核处理器上运行多达4个并发线程。


答案 2

每个处理器都有一些#number内核,每个内核可以同时运行一些#number线程。例如:如果处理器有 2 个内核,并且每个内核可以同时处理 4 个线程,则该处理器可以在任何给定的时间实例运行线程。4*2=8