Java多线程
in with 0 comment

Java多线程

in with 0 comment

线程的创建方式

继承 Thread

public class MyThread extends Thread {
    @Override
    public void run() {
        // todo...
    }
}

MyThread thread = new MyThread();
thread.start();

实现 Runnable

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // todo...
    }
}

MyThread thread = new MyThread(new MyRunnable());
thread.start();

实现 Callable

public class MyCallable impements Callable<Boolean> {
    @Override
    public Boolean call() {
        // todo...
    }
}

ExecutorService exc = Executors.newFixedThreadPool(1);
Future<Boolean> future = exc.submit(new MyCallable())

boolean res = future.get();

exc.shutdownNow();

线程的状态

方法 说明
sleep 线程休眠
yield 线程礼让,不一定成功
join 线程加入,强制执行某个线程
setPriority 设置优先级
getState 获取线程状态
setMaemon 设置为守护线程

线程锁

synchronized

class MyRunnable implements Runnable {

    private final Map<String, Integer> container;

    MyRunnable(Map<String, Integer> container) {
        this.container = container;
    }

    @Override
    public void run() {
        synchronized (container) {
            int i = container.get("key");
            System.out.println(i + 1);

            container.put("key", i + 1);
        }
    }
}

lock

public class Demo {

    private static final Map<String, Integer> container = new HashMap<>();

    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        container.put("key", 0);

        for (int i=0; i<100; i++) {
            new Thread(new MyRunnable(container, lock)).start();
        }
    }
}

class MyRunnable implements Runnable {

    private final Map<String, Integer> container;

    private final Lock lock;

    MyRunnable(Map<String, Integer> container, Lock lock) {
        this.container = container;
        this.lock = lock;
    }

    @Override
    public void run() {
        try {
            lock.lock();

            int i = container.get("key");
            System.out.println(i + 1);

            container.put("key", i + 1);
        } finally {
            lock.unlock();
        }
    }
}

描述
可重入锁 当前线程拿到锁后,还可以继续获得该锁
不可重入锁 当前线程拿到锁后,不可用继续获取该锁
乐观锁 读操作时认为数据安全,写操作时会CAS判断
悲观锁 读写操作均不信任,直接加锁
自旋锁 尝试拿锁,拿不到一直循环等待,不进入阻塞状态 lock.tryLock()
读写锁 分为读锁和写锁

线程通讯

方法 说明
wait 当前线程进入等待状态
notify 通知一个其他线程退出等待
notifyAll 通知所有其他线程退出等待
public class Demo {

    public static void main(String[] args) throws InterruptedException {
        SuperMarket superMarket = new SuperMarket();
        new Thread(new Productor(superMarket)).start();
        new Thread(new Consumer(superMarket)).start();
    }
}

class SuperMarket {

    private volatile int mac = 0;

    public synchronized void consumer() throws InterruptedException {
        if (mac == 0) {
            this.notify();
            this.wait();
        }

        System.out.printf("出货: %s%n", --mac);
    }

    public synchronized void product() throws InterruptedException {
        if (mac == 10) {
            this.notify();
            this.wait();
        }

        System.out.printf("进货: %s%n", ++mac);
    }

}

@RequiredArgsConstructor
class Productor implements Runnable {

    private final SuperMarket superMarket;

    @Override
    public void run() {
        while (true) {
            try {
                superMarket.product();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

@RequiredArgsConstructor
class Consumer implements Runnable {

    private final SuperMarket superMarket;

    @Override
    public void run() {
        while (true) {
            try {
                superMarket.consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

线程池

方法 说明
Executors.newCachedThreadPool 池中有线程就返回,没有就创建,过期回收
Executors.newFixedThreadPool 创建固定数量的线程池
Executors.newScheduledThreadPool 创建带有定时任务的线程池
Executors.newSingleThreadExector 创建只有一个线程的池