Art 1.java concurrent programming - concurrent programming challenges

1.1 context switching

  Single-core processor also supports multi-threaded code execution, CPU mechanism to achieve this by allocating CPU time slice to each thread. CPU time slice is the time allocated for each thread, since the very short time slice, the CPU is performed by constantly switching the thread.

  It will switch to the next task allocation algorithm by the CPU cycles to perform the task time slice, a time slice of the current task execution. But before a task switch will save the state so that the next state to switch back to the next task, you can then load the task, so the task to save the process from load is switched on again in the afternoon.

  It's like we read two books at the same time, when we are once again a technical book in English, we found that a word is not recognized, then open the English dictionary, but before that we need to lay down technical book write down how many pages of this book read the number of lines, words, etc. after finishing up in to continue reading this book. This switch will affect the efficiency of reading the same context switch will also affect the speed of execution of multiple threads.

1.1.1 Multithreading certain fast you

  

public class ConcurrencyTest {

    private static final long count = 100001;

    public static void main(String[] args) throws InterruptedException {
        concurrency();
        serial();
    }
    private static void concurrency() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread thread = new Thread(() -> {
            int a = 0;
            for (long i = 0; i < count; i++) {
                a += 5;
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        thread.join();
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime+"ms,b = "+b);
    }

    private static void serial(){
        long startTime = System.currentTimeMillis();

        int a = 0;
        for (long i = 0; i < count; i++) {
            a += 5;
        }
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        long endTime = System.currentTimeMillis();

        System.out.println(endTime - startTime+"ms,b = "+b+"---a="+a);
    }
}

  

  Found from the table, when executed concurrently when the operation does not accumulate more than a million times, the speed will be slower than serial execution accumulate operations, why concurrent execution speed will be slower than the serial it? This is because the overhead of thread creation and context switching.

1.1.2 Test context switching times and duration

Guess you like

Origin www.cnblogs.com/panda777/p/11295094.html