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

送分小仙女□ 提交于 2019-11-27 10:51:12

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

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

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

 

 1 public class Test1 {
 2     public static void main(String[] args) {
 3         // 假设我们要描述的是每一个线程单独分配一个任务,并行处理。那么使用继承Thread类做是实现
 4         // MyThread myThread1=new MyThread();
 5         // MyThread myThread2=new MyThread();
 6         // MyThread myThread3=new MyThread();
 7         //
 8         // myThread1.start();
 9         // myThread2.start();
10         // myThread3.start();
11         // 假设我们要描述的是一个任务多个线程共同竞争并行处理。那么使用实现Runnable接口
12         TicketWindows ticketWindows = new TicketWindows();
13         Thread thread1 = new Thread(ticketWindows, "窗口1");
14         Thread thread2 = new Thread(ticketWindows, "窗口2");
15         Thread thread3 = new Thread(ticketWindows, "窗口3");
16         thread1.start();
17         thread2.start();
18         thread3.start();
19 
20     }
21 }
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 +
    // "张");
    // }
    // }
    // }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!