本程序目的:解决卖重复票 还有 负数票的情况

来源:互联网 发布:巨浪金融研究所数据 编辑:程序博客网 时间:2024/05/21 22:25
package com.mth.synchronizedtest;/*多线程 * 本程序目的:解决卖重复票 还有 负数票的情况 * synchronized这个关键字有两种用法1、放方法名前形成同步方法;2、放在块前构成同步块。 *   * */public class SynchronizedTest1 implements Runnable {private int tickets = 100;// @Override// public void run() {// for (int i = 0; i < 50; i++) {// // 第一种同步块 实现共享// synchronized (this) {//// if (tickets > 0) {//// System.out.println(Thread.currentThread().getName()// + "号窗口卖出" + this.tickets-- + "号票");//// }// }// }// }public synchronized void run() {// 第二种 方法同步for (int i = 0; i < 50; i++) {// 同步块 实现共享if (tickets > 0) {try {Thread.sleep(5);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName() + "号窗口卖出"+ this.tickets-- + "号票");}}};public static void main(String[] args) {SynchronizedTest1 test = new SynchronizedTest1();Thread t1 = new Thread(test);Thread t2 = new Thread(test);Thread t3 = new Thread(test);Thread t4 = new Thread(test);t1.start();t2.start();t3.start();t4.start();}}

0 0
原创粉丝点击