题目:
多人参加1000米接力跑
每人跑100米,换下个选手
每跑10米显示信息
解题思路:
1.必须要用到多线程的锁,否则就会出现三个选手乱跑的情况,我们需要一个一个跑
2.使用给oneRunner上锁的方式更细的控制资源比直接给run方法上锁更精确。
子线程:
package JieLiRun;
public class Runner implements Runnable{
private Integer Long = 300;//一共300米
@Override
public void run() {
if (Long>0){
oneRunner();
}
}
public synchronized void oneRunner(){
System.out.println(Thread.currentThread().getName()+"拿到接力棒");
for (int i = 10;i<=100;i+=10){
System.out.println(Thread.currentThread().getName()+"跑了"+i+"米");
}
Long-=100;
}
}
主线程:
package JieLiRun;
public class RunnerTest {
public static void main(String[] args) {
Runner runner = new Runner();
Thread thread1 = new Thread(runner,"1号选手");
Thread thread2 = new Thread(runner,"2号选手");
Thread thread3 = new Thread(runner,"3号选手");
thread1.start();
thread2.start();
thread3.start();
}
}