欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程_抢票_龟兔赛跑

程序员文章站 2022-05-02 10:38:48
...

多线程_抢票_龟兔赛跑

package com.sxt.thread;
/**
 * 共享资源,并发(线程安全)
 * 
 * @author 
 *
 */
public class Web12306 implements Runnable{
	//票数
	private int ticketNums = 99;
	
	@Override
	public void run() {
		while(true) {
			if(ticketNums<0) {
				break;
			}
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"-->"+ticketNums--);
		}
	}
	public static void main(String[] args) {
		//一份资源
		Web12306 web =new Web12306();
		System.out.println(Thread.currentThread().getName());
		//多个代理
		new Thread(web,"码畜").start();
		new Thread(web,"码农").start();
		new Thread(web,"码蟥").start();;
	}
}


package com.sxt.Thread;
/**
 * 模拟龟兔赛跑
 * @author 
 *
 */
public class Racer implements Runnable{
	private String winner;//胜利者

	@Override
	public void run() {
		for(int steps=1;steps<=100;steps++) {
			//模拟休息
			if(Thread.currentThread().getName().equals("tuzi")&&steps%10==0) {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName()+"-->"+steps);
			//比赛是否结束
			if(gameOver(steps)) {
				break;
			}
		}
	}
	public boolean gameOver(int steps) {
		if(winner!=null) {//存在胜利者
			return true;
		}else {
			if(steps==100) {
				winner = Thread.currentThread().getName();
				System.out.println("winner"+"-->"+winner);
				return true;
			}
		}
		return false;
	}
	public static void main(String[] args) {
		Racer racer = new Racer();
		new Thread(racer,"wugui").start();
		new Thread(racer,"tuzi").start();
	}
	
}