开发者

Can't get java to use more than one core

开发者 https://www.devze.com 2023-04-11 15:40 出处:网络
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

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号