Java 一次可以在CPU上运行多少个线程
我想知道对于一个应用程序,一个CPU上可以同时运行多少个线程 我也很简单,比如:Java 一次可以在CPU上运行多少个线程,java,multithreading,Java,Multithreading,我想知道对于一个应用程序,一个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 a
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.");
}
}
然后显示如下输出:
子线程创建编号:99
子线程运行时间:5 99 Sun May 26 21:02:32 IST 2013
子线程运行:499 Sun May 26 21:02:32 IST 2013
子线程运行:399 Sun May 26 21:02:33 IST 2013
子线程运行:299 Sun May 26 21:02:33 IST 2013
子线程运行:1999 Sun May 26 21:02:34 IST 2013
那么,如果我在代码中添加一行简单的代码,那么它表明只有两个线程可以访问两个处理器,这怎么可能呢?这取决于您所说的“同时”是什么意思。您可以通过切换在同一个处理器上执行无限多的线程,也就是说,从一个线程执行一行代码,然后切换到另一行,执行一行代码,然后切换回。处理器通过非常快速地来回切换来模拟“同时执行”
然而,大多数处理器的可执行的真正同步线程数量仅限于它们拥有的内核数量,但由于共享资源和硬件,这也是一个错误的估计。理论上,一个4核处理器上最多可以同时运行4个线程。每个处理器都有一定数量的内核,每个内核可以同时运行一定数量的线程。例如:如果一个处理器有2个内核,并且每个内核一次可以同时处理4个线程,那么该处理器可以在任何给定的时间实例上运行
4*2=8
线程。显示时间直到秒。线程切换的速度要快得多,所以您在这里没有注意到。当你做“睡眠”时,线程不会占用CPU,它可以自由地执行其他东西。如果你说的“CPU”是指“一个执行单元”,那么答案是一个。但是,计划在一个执行单元上运行的线程数可以超过一个。您的时间分辨率太小。你应该以纳秒为单位打印结果。每个线程也会消耗其堆栈的内存。在windows上,默认值为1MB。因此,线程的数量也受到可用内存的限制。是的,无限受限于机器和服务器的资源os@jason如果我像t.start()那样修改代码;t、 join();然后显示如下输出:子线程创建编号:99 99 99子线程运行:5 99 Sun May 26 21:02:32 IST 2013子线程运行:4 99 Sun May 26 21:02:32 IST 2013子线程运行:3 99 Sun May 26 21:02:33 IST 2013子线程运行:2 99 Sun May 26 21:02:33 IST 2013子线程运行:1 99 Sun May 26 21:02:34 IST 2013那么它是如何运行的呢如果我在代码中添加一个简单的行,那么它可能表明只有2个线程可以访问2个处理器?
t.start();
t.join();