交替打印数字和字⺟

问题描述

使⽤两个线程交替打印序列,⼀个线程打印数字, 另外⼀个线程打印字⺟, 最终效果 如下:

12AB34CD56EF78GH910IJ1112KL1314MN1516OP1718QR1920ST2122UV2324WX2526YZ2728

解题思路

通过线程通信,通知2个线程依次打印2个自己的内容即可,打印后通知另1个线程打印

golang 方案

package program

import (
    "sync"
    "testing"
)

func Test_1(t *testing.T) {
    char := make(chan bool)
    number := make(chan bool)

    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        i := 1
        for {
            select {
            case <-number:
                print(i)
                i++
                print(i)
                i++
                char <- true
            }
        }
    }()

    go func() {
        i := 'A'
        for {
            select {
            case <-char:
                if i > 'Z' {
                    wg.Done()
                    return
                }
                print(string(i))
                i++
                print(string(i))
                i++
                number <- true
            }
        }
    }()

    number <- true
    wg.Wait()

}

java方案

public class Test1 {
    public static void main(String[] args) throws InterruptedException {

        Lock lock = new ReentrantLock();
        Condition number = lock.newCondition();
        Condition chars = lock.newCondition();
        CountDownLatch countDownLatch = new CountDownLatch(1);

        Runnable numberPrinter = () -> {
            int i = 1;
            while (true) {
                lock.lock();
                System.out.print(i);
                i++;
                System.out.print(i);
                i++;
                chars.signal();
                try {
                    number.await();
                } catch (InterruptedException e) {
                    System.out.println("Interrupt");
                } finally {
                    lock.unlock();
                }
            }
        };

        Runnable charPrinter = new Runnable() {
            int i = 'A';

            @Override
            public void run() {
                while (true) {
                    lock.lock();
                    if (i > (int) 'Z') {
                        countDownLatch.countDown();
                        return;
                    }
                    System.out.print((char) i);
                    i++;
                    System.out.print((char) i);
                    i++;
                    number.signal();
                    try {
                        chars.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } finally {
                        lock.unlock();
                    }
                }

            }
        };
        Thread t1 = new Thread(charPrinter);
        Thread t2 = new Thread(numberPrinter);

        t1.start();
        t2.start();
        countDownLatch.await();
        System.exit(1);
    }
}

Python方案

import threading

lock = threading.Lock()
number_condition = threading.Condition(lock)
char_condition = threading.Condition(lock)


def number_print():
    i = 1
    while True:
        lock.acquire()
        print(i, end='')
        i += 1
        print(i, end='')
        i += 1
        char_condition.notify()
        number_condition.wait()
        lock.release()


def char_print():
    i = ord('A')
    while True:
        if i > ord('Z'):
            return
        lock.acquire()
        print(chr(i), end='')
        i += 1
        print(chr(i), end='')
        i += 1
        number_condition.notify()
        char_condition.wait()
        lock.release()


threading.Thread(target=number_print).start()
threading.Thread(target=char_print).start()

results matching ""

    No results matching ""