package com.csi.homework09;
/**
* 某公司组织年会,会议入场时有两个入口,假设公司有100个员工, 利用多线程模拟年会入场过程,并分别统计每个入口入场的人数。
* 线程运行后打印格式如下:
* 编号为: 2 的员工 从后门 入场!
* 编号为: 1 的员工 从后门 入场!
* ......
* 从后门入场的员工总共: 13 位员工
* 从前门入场的员工总共: 87 位员工
*
* @author 86152
*
*/
public class PrintThread implements Runnable {
public static int x = 1;
public static int qian =0;
public static int hou = 0;
@Override
public void run() {
while(true){
if(x<100){
//99
synchronized(this){
if(Thread.currentThread().getName().equals("前门")){
System.out.println("编号为:"+x+"的员工 从前门 入场");
x++;
qian++;
}else if(Thread.currentThread().getName().equals("后门")){
System.out.println("编号为:"+x+"的员工 从后门 入场");
x++;
hou++;
}
}
}else{
break;
}
}
}
}
package com.csi.homework09;
public class TestPrint {
public static void main(String[] args) {
PrintThread pt = new PrintThread();
Thread th1 = new Thread(pt,"前门");
Thread th2 = new Thread(pt,"后门");
th1.start();
th2.start();
try {
th1.join();
th2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("从后门入场的员工总共:"+PrintThread.hou+"位员工");
System.out.println("从前门入场的员工总共:"+PrintThread.qian+"位员工");
}
}
1.某公司组织年会,会议入场时有两个入口,假设公司有100个员工,利用多线程模拟年会入场过程,并分别统计每个入口入场的人数。线程运行后打印格式如下: 编号为: 2 的员工 从后门 入场! 编号为: 1
最新推荐文章于 2022-01-05 11:35:37 发布