---恢复内容开始---
(1)加深对进程并发执行的理解,认识多进程并发执行的实质。
(2)观察进程共享资源的现象,学习解决进程互斥和同步的方法。
本实验要求用高级语言,启动多进程并发运行,设计相应代码,显示进程无关并发、进程共享变量并发的运行结果。并完成实验报告。
三、实验内容:
分别实现以下四种情况的并发:
1.并发的进程之间无关,显示进程名称,开始与结束时间。
模拟多终端售票情况,并发的多个终端进程之间共享剩余票数这个共享变量。
2.用全局变量实现。
3.用进程间共享数据机制实现。
4.用进程间共享数据机制和加锁机制实现。
四、实验过程与结果
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public class ThreadTest3 { public static void main(String[] args) { Shop shop = new Shop(); for (int i = 1; i <= 5; i++) { new Thread(shop,"").start(); } }}class Shop implements Runnable{ String name; ticket t; public Shop() { t.total = 100; t.count = 0; } public void run() { while (t.total>0) { synchronized (this) { try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"_____"+t.count); t.total--; t.count++; } } }}class ticket { int total; int count;} |
通过共享变量实现
import os
import threading
tickis=1000
lock=threading.Lock()
def sale_tickis(thread_name):
global tickis
global lock
while 1:
lock.acquire()
if tickis!=0:
tickis-=1
print(thread_name,"余票为:",tickis)
else:
print(thread_name,"票卖完了")
os._exit(0)
lock.release()
class my_thread(threading.Thread):
def __init__(self,name=""):
threading.Thread.__init__(self)
self.name=name
def run(self):
sale_tickis(self.name)
if __name__=="__main__":
for i in range(1,21):
thread = my_thread("线程" + str(i))
thread.start()
原文:https://www.cnblogs.com/ze-ze/p/10896466.html