- Why doesn't it use all of the processor?
- import javax.swing.JTextPane;
- public class Main {
- static int numberToCalculate = 100;
- static int otherNumberToCalculate = 50;
- static String typeOfCalculation = "all";
- static int calculated;
- static int calculations = 10000000;
- public static void calculate(JTextPane j, JTextPane j2) {
- long time = System.currentTimeMillis();
- for(int i = 0; i <= calculations; i++) {
- switch(typeOfCalculation) {
- case "Divide":
- calculated = numberToCalculate / otherNumberToCalculate;
- break;
- case "Multiply":
- calculated = numberToCalculate * otherNumberToCalculate;
- break;
- case "Plus":
- calculated = numberToCalculate + otherNumberToCalculate;
- break;
- case "Minus":
- calculated = numberToCalculate - otherNumberToCalculate;
- break;
- case "All":
- calculated = numberToCalculate / otherNumberToCalculate;
- calculated = calculated * otherNumberToCalculate;
- calculated = calculated + otherNumberToCalculate;
- calculated = calculated - otherNumberToCalculate;
- break;
- default:
- Test.UpdateText(j, "Error, please pick type of calculation.");
- Test.UpdateText(j2, "Error, please pick type of calculation.");
- break;
- }
- if(i == calculations) {
- Test.UpdateText(j, "Milliseconds: " + (System.currentTimeMillis() - time));
- Test.UpdateText(j2, "Result: " + calculated);
- }
- }
- }
- public static void main(String [] args)
- {
- Test.window();
- }
- }
- public static void main(String[] args) {
- ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
- Runnable r = new Runnable() {
- @Override
- public void run() {
- double sum = 0;
- for (int i = 1; i < 100000000; i++) {
- sum += Math.log(i);
- }
- System.out.println(sum);
- }
- };
- r.run(); //first run: single thread
- //second run: as many threads as processors
- for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
- executor.submit(r);
- }
- executor.shutdown();
- }