Can't get java to use more than one core
I'm working on a concurrency assignment that involves parallelizing a problem for performance. The problem involves a fair amount of blocking i/o so for my report I want to use and compare cpu usage of various approaches.
I'm new to profiling and I've started off with Java's vitual vm, but even with multiple threads running a tight loop with no blocking I can't seem to get 开发者_StackOverflow中文版above 50% cpu usuage. This would seem to be that only one of my two cores is being used.
How do I get my threads to use both cores? I've tried both manually creating threads and using the executor framework.
Thanks in advance
I don't know what your code is doing, but this manages to put all my cores up to 100%...
import java.util.concurrent.*;
public class Test implements Runnable {
public static void main(String[] args) throws InterruptedException {
Test task = new Test();
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
pool.submit(task);
}
pool.awaitTermination(120, TimeUnit.SECONDS);
}
@Override public void run() {
System.out.println("Task running...");
int i = 0;
while (true) {
i++;
}
}
}
int processors = Runtime.getRuntime().availableProcessors();
for(int i=0; i < processors; i++) {
Thread yourThread = new AThreadYouCreated();
// You may need to pass in parameters depending on what work you are doing and how you setup your thread.
yourThread.start();
}
in this way you can solve your problem!
精彩评论