Multithreaded Algorithms: Printing Zero and Even Numbers

 Topic understanding:

That is, there are three threads and three methods in total, and each thread will only execute one method, because the switching of threads is beyond our control. This is what the operating system does. What we have to do is when switching to the output When the thread is running, let him output. If it is not the thread's turn to output, let the CPU let other threads execute.

01020304: Assume that thread A executes the method of outputting 0, thread B executes the method of outputting odd numbers, and thread C executes the method of outputting even numbers. Then switch to thread B at the beginning but output 0 first, so thread B should give up the CPU at this time, and let the operating system choose the thread again. If thread A is selected, after executing the method (output 0), give up the CPU, etc. When randomly assigned to thread B, let him execute and output an odd number 1. The specific output implementation is realized by the parameter passing in the method, which does not require our relationship, we only need to call printNumber.accept (the number to be output). Don't need to worry too much here

The following is the code implementation:

class ZeroEvenOdd {
    private int n;    //这个是要输出到哪个数值
    private int i=1;    //这个记录的是要输出的数值
    private boolean b = true;    //为true时要输出的是0,为false时要输出具体数字i
    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        while(true){
            if(i==n+1){    //当n这个数字也已经输出时就退出循环
                break;
            }
            if(b){
                printNumber.accept(0);   //输出0
                b=false;
            }else{
                Thread.yield();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while(true){
            if(i==n+1){
                break;
            }
            if(!b){    //如果为false就说明该输出0了,就让出CPU。
            if(i%2==0){//判断是否是偶数,如果不是就让出CPU
                printNumber.accept(i);//输出i
                b=true;
                i++;
            }else{
                Thread.yield();//让出CPU
            }
            }else{
                Thread.yield();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        while(true){
            if(i==n+1){
                break;
            }
            if(!b){
            if(i%2==1){
                printNumber.accept(i);
                b=true;
                i++;
            }else{
                Thread.yield();
            }
        }else{
                Thread.yield();
            }
            
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_64680177/article/details/131898597