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