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

我想知道同一个应用程序可以在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  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日太阳5月26日19:23:19 2013年IST

Child Thread Run:1 2 Sun May 26 19:23:19 IST 2013

Child Thread Run:1 1 Sun May 26 19:23:19 IST 2013

Child Thread Run:1 3 Sun May 26 19:23:19 IST 2013

Child Thread Run:1 0 Sun May 26 19:23:19 IST 2013

Child Thread Run:1 4 Sun May 26 19:23:19 IST 2013

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

这怎么可能?

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

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

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

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

然后它显示输出如:

Child thread Creation NO:99 99 Child Thread Run:5 99 Sun May 26 21:02:32 IST 2013

Child Thread Run:4 99 Sun May 26 21:02:32 IST 2013

Child Thread Run:3 99 Sun May 26 21:02:33 IST 2013

Child Thread Run:2 99 Sun May 26 21:02:33 IST 2013

Child Thread Run:1 99 Sun May 26 21:02:34 IST 2013

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

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

但是,大多数处理器受限于它们可以执行的真正同步线程数量,以及它们拥有的核心数量,但即使这是由于共享资源和硬件而导致的错误估计。 理论上,在4核处理器上最多可以同时运行4个线程。