JAVA随想:单一任务与多线程关系

参考车票窗口买票系统DAY17-190807

1.多个线程单一任务(每一个线程有且只有一个任务匹配)-假设一个车票系统里有三个车票窗口(一个窗口有50张车票,共有150张车票)分别单独各自卖票(只卖自己窗口的50张票)(相比2,均衡卖车票,各自卖票数概率相等)

2.一个任务多个线程(任务内可以多个线程互斥竞争掠夺资源)-假设一个车票系统(一个车票系统里共150张车票)有三个车票窗口共同互斥竞争卖车票(相比1,随机抢车票,各自卖票数概率不一定相等)

public class TicketWindows implements Runnable {

	private Integer nums = 5000;

	@Override
	public void run() {
		// 1.synchronized修饰方法中,代表该方法同一时刻只能一个线程 进来
		// 2.synchronized代码块,synchronized锁住的对象必须是所有线程所共有
		// synchronized (Thread.currentThread().getName()) {
		// }
		while (nums > 0) {
			synchronized (this) {
				if (nums > 0) {
					nums--;
					System.out.println(Thread.currentThread().getName() + "卖了一张票。剩下" + nums + "张");
				}

			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	// @Override
	// public void run() {
	// // TicketWindows.class获取TicketWindows.class文件
	// synchronized (TicketWindows.class) {
	// // 1.synchronized修饰方法中,代表该方法同一时刻只能一个线程 进来
	// // 2.synchronized代码块,synchronized锁住的对象必须是所有线程所共有
	// // synchronized (Thread.currentThread().getName()) {
	// // }
	// while (nums > 0) {
	// nums--;
	// System.out.println(Thread.currentThread().getName() + "卖了一张票。剩下" + nums +
	// "张");
	// }
	// }
	// }

}
public class Test1 {
	public static void main(String[] args) {
		// 假设我们要描述的是每一个线程单独分配一个任务,并行处理。那么使用继承Thread类做是实现
		// MyThread myThread1=new MyThread();
		// MyThread myThread2=new MyThread();
		// MyThread myThread3=new MyThread();
		//
		// myThread1.start();
		// myThread2.start();
		// myThread3.start();
		// 假设我们要描述的是一个任务多个线程共同竞争并行处理。那么使用实现Runnable接口
		TicketWindows ticketWindows = new TicketWindows();
		Thread thread1 = new Thread(ticketWindows, "窗口1");
		Thread thread2 = new Thread(ticketWindows, "窗口2");
		Thread thread3 = new Thread(ticketWindows, "窗口3");
		thread1.start();
		thread2.start();
		thread3.start();

	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值