实验--多线程
来源:互联网 发布:和飞行员谈恋爱 知乎 编辑:程序博客网 时间:2024/05/22 03:14
实验目标:
1、掌握线程和多线程的概念
2、掌握创建线程的两种方法及其区别
3、了解线程的启动、终止、同步、互斥和优先级等概念
实验内容:1、编写一个程序,其功能是运行之后,其中有一个线程可以输出20次你的学号,另一个线程会输出20次你的姓名。
思考:如何实现打印所有的学号之后再打印姓名?
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApplication1{ class MyThread { private string id="250129131"; private string name = "zhang"; private int flag; public MyThread(int ff) { flag = ff; } public void disp() { if (flag == 0) { for (int j = 0; j < 20; j++) { Console.WriteLine(id); Thread.Sleep(20); } } else { for (int j = 0; j < 20; j++) { Console.WriteLine(name); Thread.Sleep(20); } } } } class Program { static void Main(string[] args) { MyThread thread1 = new MyThread(1); MyThread thread2 = new MyThread(0); Thread objThread1 = new Thread(new ThreadStart(thread1.disp)); Thread objThread2 = new Thread(new ThreadStart(thread2.disp)); objThread1.Start(); objThread1.Join(); objThread2.Start(); Console.ReadLine(); } }}
2、编写程序实现火车票售票程序。要求如下:
(1)假设列车的座号为1-60,车票按照座号依次售出
(2)有四个窗口可以同时售票(即:创建四个线程)
(3)每个窗口都有20个人排队买票
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApplication2{ class MyThread { static int count = 1; public void sellTic() { for (int i = 0; i < 20; i++) { lock (this) { if (count > 60) Console.WriteLine("{0}的第{1}个人来买票,票已售完!",Thread.CurrentThread.Name,i+1); else { Console.WriteLine("{0}的第{1}个人来买票,得到了第{2}号票!", Thread.CurrentThread.Name, i+1,count); count++; Thread.Sleep(10); } } } } } class Program { static void Main(string[] args) { MyThread obj = new MyThread(); Thread th1 = new Thread(new ThreadStart(obj.sellTic)); th1.Name = "窗口1"; Thread th2 = new Thread(new ThreadStart(obj.sellTic)); th2.Name = "窗口2"; Thread th3 = new Thread(new ThreadStart(obj.sellTic)); th3.Name = "窗口3"; Thread th4 = new Thread(new ThreadStart(obj.sellTic)); th4.Name = "窗口4"; th1.Start(); th2.Start(); th3.Start(); th4.Start(); Console.ReadLine(); } }}
1 0
- 多线程实验
- 实验--多线程
- java 多线程实验
- 实验题目:多线程
- java多线程简单实验
- C#多线程实验
- 实验一 多线程
- c++多线程实验代码
- Java多线程实验
- OpenMP多线程编程实验
- 多线程编程实验
- 实验11 多线程
- 多线程访问Vector一个实验
- java多线程--买票(ticket)实验
- java多线程实验 滚动字
- Linux下多线程程序设计实验
- java实验7-多线程编程
- python多线程编程例子实验
- android studio的gradle说解
- showModalDialog chrome 新版本解决方案
- 简易Java(18):属性能否重写?为什么?
- Action中访问Servlet API
- iOS开发多线程篇—GCD的常见用法
- 实验--多线程
- 浅谈 JavaScript 编程语言的编码规范
- 点击精灵区域消除,点击其他区域创建新精灵。(模拟放置炸弹,及引爆)
- Android利用canvas画各种图形(点、直线、弧、圆、椭圆、文字、矩形、多边形、曲线、圆角矩形)
- Linux SSH远程文件/目录传输命令scp
- Linux socket文件传输2
- 黑马程序员---Java 正则表达式
- iOS之数据请求NSURLConnection
- dubbo2.5.3 dubbo:application