我想知道同一个应用程序可以在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.");
}
}
Run Code Online (Sandbox Code Playgroud)
主线:3月5日太阳5月26日19:23:19 2013年IST
Child Thread Run:1 2 Sun May 26 26: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 5月26日19:23:19 IST 2013
从输出中我们可以看到,同时五个线程可以执行(我甚至以毫秒为单位打印结果)..........我有两个处理器在程序中报告.
这怎么可能?
因为一个线程一次只能在一个CPU中运行,但它显示五个线程同时运行.
有没有办法证明只有一个线程可以同时在一个CPU中运行.......
如果我修改我的代码,如:
t.start();
t.join();
Run Code Online (Sandbox Code Playgroud)
然后它显示输出如:
子线程创建NO:99 99子线程运行: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个线程.
每个处理器都有一些#number 的内核,每个内核可以同时运行一些#number 的线程。例如:如果一个处理器有 2 个内核,并且每个内核可以同时处理 4 个线程,那么该处理器可以4*2=8在任何给定的时间实例中运行线程。
| 归档时间: |
|
| 查看次数: |
8549 次 |
| 最近记录: |