作业1:
编写多线程程序,模拟多个人通过一个山洞。这个山洞每次只能通过一个人,每个人通过山洞的时间为2秒(sleep)。随机生成10个人,都要通过此山洞,用随机值对应的字符串表示人名,打印输出每次通过山洞的人名。提示:利用线程同步机制,过山洞用一条输出语句表示,该输出语句打印输出当前过山洞的人名,每个人过山洞对应一个线程,哪个线程执行这条输出语句,就表示哪个人过山洞。
package aa;
public class Example1{
public static void main(String[] args) {
// TODO Auto-generated method stub
Text tul = new Text();
Thread people1 = new Thread(tul,"people1");
Thread people2 = new Thread(tul,"people2");
Thread people3 = new Thread(tul,"people3");
Thread people4 = new Thread(tul,"people4");
Thread people5 = new Thread(tul,"people5");
Thread people6 = new Thread(tul,"people6");
Thread people7 = new Thread(tul,"people7");
Thread people8 = new Thread(tul,"people8");
Thread people9 = new Thread(tul,"people9");
Thread people10 = new Thread(tul,"people10");
people1.start();
people2.start();
people3.start();
people4.start();
people5.start();
people6.start();
people7.start();
people8.start();
people9.start();
people10.start();
}
}
class Text implements Runnable{
private int Num = 0;
public void run(){
Cross();
}
public synchronized void Cross(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Num++;
System.out.println(Thread.currentThread().getName()+" have Crossed the river !"+" This is "+Num+"th");
}
}
第15周—多线程(作业1)
最新推荐文章于 2023-11-07 23:03:24 发布