多线程 (三) 感受并发引发的问题,如何解琐。[待补充]

63 阅读1分钟

实现一个拿票。(注意观察结果)

package com.company;

public class TestThread4 implements Runnable {
    private int ticketNum = 10;

    @Override
    public void run() {
        while (true) {
            if(ticketNum <=0) {
                break;
            }

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "--> 拿到了第" + ticketNum-- + "张票");

        }

    }

    public static void main(String[] args) {
        TestThread4 th4 = new TestThread4();
        new Thread(th4, "小明").start();
        new Thread(th4, "王老师").start();
        new Thread(th4, "黄牛党").start();

    }
}

image.png

//加关键词,确保同步安全。
public synchronized void run() { 
}

用lock 方法 。 [显示锁]

package com.company;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        TestLock2 tl2 = new TestLock2();
        new Thread(tl2).start();
        new Thread(tl2).start();
        new Thread(tl2).start();
    }
}

class TestLock2 implements Runnable{

    int ticketNum = 10;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) {
            try {
                lock.lock();
                if(ticketNum > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticketNum --;
                    System.out.println(ticketNum);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

image.png


未完待补充。 同步锁的方法 。 sychro [隐式琐,要习惯各种不同的写法。]