CPU Intensive Calculation Examples?

后端 未结 7 811
轻奢々
轻奢々 2020-12-01 05:12

I need a few easily implementable single cpu and memory intensive calculations that I can write in java for a test thread scheduler.

They should be slightly time con

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 05:46

    I was messing around with Thread priority in Java and used the code below. It seems to keep the CPU busy enough that the thread priority makes a difference.

    @Test
    public void testCreateMultipleThreadsWithDifferentPriorities() throws Exception {
        class MyRunnable implements Runnable {
            @Override
            public void run() {
                for (int i=0; i<1_000_000; i++) {
                    double d = tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(123456789.123456789))))))))));
                    cbrt(d);
                }
                LOGGER.debug("I am {}, and I have finished", Thread.currentThread().getName());
            }
        }
        final int NUMBER_OF_THREADS = 32;
        List threadList = new ArrayList(NUMBER_OF_THREADS);
        for (int i=1; i<=NUMBER_OF_THREADS; i++) {
            Thread t = new Thread(new MyRunnable());
            if (i == NUMBER_OF_THREADS) {
                // Last thread gets MAX_PRIORITY
                t.setPriority(Thread.MAX_PRIORITY);
                t.setName("T-" + i + "-MAX_PRIORITY");
            } else {
                // All other threads get MIN_PRIORITY
                t.setPriority(Thread.MIN_PRIORITY);
                t.setName("T-" + i);
            }
            threadList.add(t);
        }
    
        threadList.forEach(t->t.start());
        for (Thread t : threadList) {
            t.join();
        }
    }
    

提交回复
热议问题