- 难度级别: 简单
1) 以下程序的输出是什么?
python
复制代码
import threading barrier = threading.Barrier(4) class thread(threading.Thread): def __init__(self, thread_ID, thread_name): threading.Thread.__init__(self) self.thread_ID = thread_ID self.thread_name = thread_name def run(self): print("ThreadID = " + str(self.thread_ID) + ", ThreadName = " + self.thread_name + "\n") try: barrier = threading.Barrier(4) barrier.wait() except: print("barrier broken") thread1 = thread(100, "HY") thread2 = thread(101, "Hai") thread3 = thread(102, "Haiyong") thread1.start() thread2.start() thread3.start() barrier.wait() print("Exit")
a) ThreadID = 100, ThreadName = HY
ThreadID = 101, ThreadName = Hai
ThreadID = 102, ThreadName = Haiyong
b) ThreadID = 100, ThreadName = HY
ThreadID = 101, ThreadName = Hai
ThreadID = 102, ThreadName = Haiyong
Exit
c) 编译错误
d) 运行时错误
答:a)
解释: 这是一个死锁的例子。每个线程创建自己的屏障并在该屏障上调用 .wait() 函数。
2) 以下哪一项不是以下程序的输出?
import threading class thread(threading.Thread): def __init__(self, thread_ID, thread_name): threading.Thread.__init__(self) self.thread_ID = thread_ID self.thread_name = thread_name def run(self): print(self.thread_name) thread1 = thread(100, "HY") thread2 = thread(101, "Hai") thread3 = thread(102, "Haiyong") thread1.start() thread2.start() thread3.start() print("Exit")
a) HY Hai Haiyong 退出
b) 退出 Hai Haiyong HY
c) HY 退出 Haiyong Hai
d) 以上都不是
答:(d)
说明: 在线程上调用 start() 方法会将线程移动到就绪状态。线程调度器负责调度线程。因此,可以随时安排特定线程。
3) 以下程序的输出是什么?
import threading class thread(threading.Thread): def __init__(self, thread_ID, thread_name): threading.Thread.__init__(self) self.thread_ID = thread_ID self.thread_name = thread_name def run(self): print(self.thread_name) thread1 = thread(100, "HY") thread2 = thread(101, "Hai") thread3 = thread(102, "Haiyong ") thread = [] thread.append(thread1) thread.append(thread2) thread.append(thread3) thread1.start() thread2.start() for thread in thread: thread.join() thread3.start() print("Exit")
答。 (C)
说明: 无法在尚未开始执行的线程上调用 join() 方法。
4)以下程序的输出是什么?
import threading i = 5 class thread(threading.Thread): def __init__(self, thread_ID, thread_name): threading.Thread.__init__(self) self.thread_ID = thread_ID self.thread_name = thread_name def run(self): i = i + 1 print(i) thread1 = thread(100, "HY") thread2 = thread(101, "Hai") thread1.start() thread2.start()
a) 66
b) 67
c) 编译错误
d) 运行时错误
答: (d)
说明: 每个线程都有自己的内存保留空间。因此,对于每个线程,thread1 和 thread2,变量 temp 未声明,因为 temp 未在线程的 run 方法中定义。
5) 以下程序的输出是什么?
import threading class thread(threading.Thread): def __init__(self, thread_ID): self.thread_ID = thread_ID def run(self): print(self.thread_ID) thread1 = thread(100) thread1.start()
a) 100
b) 编译错误
c) 运行时错误
d) 这些都不是
答:(C)
说明: thread.__init__()
必须由在 __init__
函数中创建的每个线程显式调用。