如何让我的线程使用100%的CPU?

时间:2013-11-02 00:35:12

标签: java multithreading cpu-usage

我有一个简单的Producer(1)和consumer(从1-50变化)问题,其中Producer只是在Queue中添加元素并且消费者读取它。我试图获得100%的CPU利用率。

目前我的利用率为20%。而且我无法获得100%的CPU利用率。我希望我用的所有CPU都能更快地执行操作。我该怎么看?

机器:运行Windows 8和Java 7的i7(第4代 - 带超线程的四码)。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;
/*
 * Purpose is to test system clock granularity
 */

public class ClockGranularity{
        private static final int MaxExecutionTimeMsec = 6;
        //60*1000 milliseconds
        private static float delta = 0.01f;
        //Inter-arrival Time(IAT): in milliseconds
        static final int ArraySize =(int) ((float)MaxExecutionTimeMsec/delta);
        private static final int convertMilliToNano = 1000000;

        private static String getTime() {
                DateFormat format = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                return format.format(cal.getTime());
        }
        /*
         * Invoke 1 producer vs 1,2,3 consumers
         * Write consumer to file
         */
        public static void main(String args[]) {
                ClockGranularity.delta = delta*convertMilliToNano;
                long execStartTime = System.currentTimeMillis();
                long experimentStartTime = System.nanoTime();
                long execDuration, experimentRuntime;
                Buffer requestQueue = new Buffer();
                Producer producer = new Producer(requestQueue);
                Consumer consumer = new Consumer(requestQueue);
                Consumer consumer2 = new Consumer(requestQueue);
                Consumer consumer3 = new Consumer(requestQueue);
                consumer.start();
                consumer2.start();
                consumer3.start();
                do {
                        execDuration = System.currentTimeMillis() - execStartTime;
                        experimentRuntime = System.nanoTime() - experimentStartTime;
                        if(experimentRuntime >= delta) {
                                experimentStartTime = System.nanoTime();
                        producer.run();
                        }
                } while (execDuration <= MaxExecutionTimeMsec);
                consumer.interrupt();
                consumer2.interrupt();
                consumer3.interrupt();
                delta/=convertMilliToNano;
                try {
                        String producerFile = "Producer-" + delta + " msec @" + getTime();
                        printToFile(producerFile,requestQueue.getQueue());
                        String consumerFile = "Consumer-" + delta + " msec@" + getTime();
                        printToFile(consumerFile, consumer.getValidateConsumerArray());
                        consumerFile = "Consumer2-" + delta + " msec@" + getTime();
                        printToFile(consumerFile, consumer2.getValidateConsumerArray());
                        consumerFile = "Consumer3-" + delta + " msec@" + getTime();
                        printToFile(consumerFile, consumer3.getValidateConsumerArray());
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }
        public static void printToFile(String outputFileName,Queue<Integer> requestQueue) throws IOException{
                outputFileName = outputFileName.replace(':', '-');
                String lineSeparator = System.lineSeparator();
                File directory = new File("Practice Coding\\src\\ClockGranularity Test results\\Semaphore and Queue\\");
                File file = File.createTempFile(outputFileName, ".txt",directory);
                FileWriter writer = new FileWriter(file);
                writer.append("Index \tQueue Contents" + lineSeparator);
                int size = requestQueue.size();
                String summary = "queue<>" + size;
                for(int i = 0; i<size; i++) {
                        String temp = i + " ticks  \t" + requestQueue.poll();
                        System.out.println(temp);
                        writer.append(temp + lineSeparator);
                }
                writer.append(lineSeparator + "Summary: " + lineSeparator);
                writer.append(summary + lineSeparator);
                System.out.println(outputFileName + " " + summary);
                writer.close();
        }
}
class Buffer {
        private Queue<Integer> requestsQueue;
        Semaphore accessQueue;
        Buffer() {
                requestsQueue = new LinkedList<Integer>();
                accessQueue = new Semaphore(1);
        }
        public void put(Integer tick) throws InterruptedException {
                accessQueue.acquire();
                requestsQueue.add(tick);
                accessQueue.release();
        }
        public synchronized int get() throws InterruptedException {
                int tick;
                while(requestsQueue.size() == 0) {
                        try {
                                wait();
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
                accessQueue.acquire();
                tick = requestsQueue.poll();
                accessQueue.release();
                return tick;
        }
        public Queue<Integer> getQueue() {
                return requestsQueue;
        }
}

class Consumer extends Thread{
        private Buffer bufferQueue;
        private Queue<Integer> validateConsumer;
        Consumer(Buffer requestQueue) {
                bufferQueue = requestQueue;
                validateConsumer = new LinkedList<Integer>();
        }
        public void run() {
                while(true) {
                        int i;
                        try {
                                i = bufferQueue.get();
                                validateConsumer.add(i);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
        }
        public Queue<Integer> getValidateConsumerArray() {
                return validateConsumer;
        }
}

class Producer extends Thread{
        public int tick = 0;
        private Buffer bufferQueue;
        Producer(Buffer requestQueue) {
                bufferQueue = requestQueue;    
        }
        public void run() {
                try {
                        bufferQueue.put(tick++);
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
        }
}

2 个答案:

答案 0 :(得分:1)

你可以做的事情:

- 而不是做繁忙的循环(查询时间可能会降低你的利用率),看看是否存在差异,如果你把生产者代码代码放在while(true)就像你对消费者那样,睡觉主线程对于MaxExecutionTimeMsec时间,并像生产消费者一样对生产者进行中断。

- 这是典型用法的后退,但运行特殊分析器,看看花了多少时间。如果它不是业务部门(比如说等待锁定获取),那就进行重新设计。

- 如果性能是关键并且你有一个多核p,你可能想要研究自旋锁 处理器。在一些摊销的情况下,上下文切换可能比自旋锁更昂贵。

答案 1 :(得分:1)

您的Buffer实施错误。它本质上是序列化读/写,因此性能很糟糕。您需要使用或实现reader-writer lock