其它:多线程实现交替输出0和1

主要思路:使用一个输出标志和一个锁来实现,进入输出临界区代码需要先获取锁,然后判断标志位是否正确,需要考虑标志位的转化。

python实现

import threading
flag = 0
def print1(lock):
    global flag
    while True:
        with lock:
            if flag==1:
                print("I'm 1")
                flag=0

def print0(lock):
    global flag
    while True:
        with lock:
            if flag==0:
                print("I'm 0")
                flag=1

def print1V1(con):
    global flag
    while True:
        with con:
            if flag==0:#如果标志为0,等待
                con.wait()
            print("I'm 1")
            flag =0
            con.notify()


def print0V1(con):
    global flag
    while True:
        with con:
            if flag==1:#如果标志位1,等待
                con.wait()
            print("I'm 0")
            flag=1
            con.notify()



if __name__=="__main__":
    
    #使用锁Lock实现交替输出01
    lock = threading.Lock()
    t0 = threading.Thread(target=print0,args=(lock,))
    t1 = threading.Thread(target=print1,args=(lock,))
    t0.start()
    t1.start()
    
    # 使用条件Condition实现交替输出01
    con = threading.Condition()
    t0v1 = threading.Thread(target=print0V1,args=(con,))
    t1v1 = threading.Thread(target=print1V1,args=(con,))
    t0v1.start()
    t1v1.start()

Java实现

public class Output01 {
    private static int flag = 0;

    public static void main(String[] args) {
        Output01 output01 = new Output01();

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (output01){
                        if(flag==0){
                            System.out.println(0);
                            flag=1;
                            output01.notify();
                        }else {
                            try {
                                output01.wait();
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }

                    }
                }

            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (output01){
                        if(flag==1){
                            System.out.println(1);
                            flag=0;
                            output01.notify();
                        }else {
                            try {
                                output01.wait();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }

                    }
                }

            }
        });

        thread1.start();
        thread2.start();
    }
}

你可能感兴趣的:(其它:多线程实现交替输出0和1)