题解 | #多线程#

多线程

http://www.nowcoder.com/practice/cd99fbc6154d4074b4da0e74224a1582

import threading

def initInput():
    while True:
        try:
            yield int(input())
        except EOFError:
            break

class MyThread(threading.Thread):
    def __init__(self, c1, c2, n, arr, lock, s=False):
        super(MyThread, self).__init__()
        self.c1 = c1      # 上一个字符(根据上个字符确定是否需要输入下个字符)
        self.c2 = c2      # 下个字符
        self.max_n = n      # 最多需要输入多少个字符
        self.n = 0      # 初始已经输入的字符数量
        self.lock = lock      # 线程锁,防止线程串掉
        self.arr = arr      # 输入数据的的数组
        self.s = s          # 是否需要打印出结果

    def run(self):
        while self.n < self.max_n:
            self.lock.acquire()     # 获取锁
            if self.arr[-1] == self.c1:
                self.arr.append(self.c2)
                self.n += 1     
            self.lock.release()     # 释放锁
        if self.s:
            print(''.join(self.arr))

class MT1(MyThread):

    def __init__(self, n, arr, lock):
        super(MT1, self).__init__('D', 'A', n, arr, lock)
class MT2(MyThread):

    def __init__(self, n, arr, lock):
        super(MT2, self).__init__('A', 'B', n, arr, lock)
class MT3(MyThread):

    def __init__(self, n, arr, lock):
        super(MT3, self).__init__('B', 'C', n, arr, lock)
class MT4(MyThread):

    def __init__(self, n, arr, lock):
        super(MT4, self).__init__('C', 'D', n, arr, lock, True)

def func(n):
    arr = ['A']
    lock = threading.Lock()
    ths = [
    MT2(n, arr, lock), 
    MT3(n, arr, lock), 
    MT4(n, arr, lock), 
    MT1(n-1, arr, lock)]  # A已经默认输入了一个,所以需要少一个
    for i in ths:
        i.start()
    for i in ths:
        i.join()
for n in initInput():
    func(n)
全部评论

相关推荐

11-24 19:04
已编辑
湖南工商大学 Java
点赞 评论 收藏
分享
双非硬上算法:洗洗睡吧,说多了都是遗憾,说白了都是扯淡
点赞 评论 收藏
分享
评论
6
1
分享
牛客网
牛客企业服务