手撕Java多线程(二)基础线程机制

基础线程机制

Executor

Executor管理多个异步任务的执行,而无需显示地管理线程的生命周期。这里的异步是指多个任务的执行互不干扰,不需要进行同步操作。
主要有三种Executor:

  • CachedThreadPool:一个任务创建一个线程;
  • FixedThreadPool:所有任务只能使用固定大小的线程池;
  • SignalThreadExecutor:相当于大小为1的FixedThreadPool;
@Data
@AllArgsConstructor
class Task implements Callable<String> {
    private String taskName;

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread() + "|" + taskName);
        return "hello" + "|" + taskName;
    }
}

@Test
void test3() throws ExecutionException, InterruptedException {
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
        Task task = new Task("task" + i);
        FutureTask<String> futureTask = new FutureTask<>(task);
        executorService.execute(futureTask);
        System.out.println(futureTask.get());

    }
    executorService.shutdown();
}
Thread[pool-2-thread-1,5,main]|task0
hello|task0
Thread[pool-2-thread-2,5,main]|task1
hello|task1
Thread[pool-2-thread-2,5,main]|task2
hello|task2
Thread[pool-2-thread-2,5,main]|task3
hello|task3
Thread[pool-2-thread-2,5,main]|task4
hello|task4
Thread[pool-2-thread-2,5,main]|task5
hello|task5
Thread[pool-2-thread-2,5,main]|task6
hello|task6
Thread[pool-2-thread-2,5,main]|task7
hello|task7
Thread[pool-2-thread-2,5,main]|task8
hello|task8
Thread[pool-2-thread-2,5,main]|task9
hello|task9

调用execute()方法,来调用线程任务。

CachedThreadPool:一个任务创建一个线程;

会根据任务数量来创建相应的线程数,不过CachedThreadPool的核心线程数默认为0,所以可想而知,这些创建出来

  • FixedThreadPool:所有任务只能使用固定大小的线程池;
  • SignalThreadExecutor:相当于大小为1的FixedThreadPool;

Daemon守护线程

守护线程是程序运行时在后台提供服务的线程,不属于程序中不可或缺的部分。
当所有的非守护线程个结束时,程序也就终止,同时会杀掉所有守护线程。
使用setDaemon()方法将一个线程设置为守护线程。
main()属于非守护线程。

sleep()方法

Thread.sleep(millisec) 方法会休眠当前正在执行的线程,millisec单位为毫秒。

sleep()可能会抛出InterruptedException,因为异常不能垮线程传播回main()中,因此必须在本地进行处理。线程中抛出的其它异常也同样需要在本地进行处理。

public void run() {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

yield()方法

对静态方法Thread.yield()的调用声明了当前线程已经完成了生命周期中最重要的部分,可以切换给其他线程来执行。该方法只是对线程调度器的一个建议,而且也只是建议具有相同优先级的其他线程可以运行。

public void run() {
    Thread.yield();
}

线程中断

一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束。

InterruptedException

通过调用一个线程的interrupt()来中断该线程,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出InterruptedException,从而提前结束该线程。但是不能中断I/O阻塞和synchronized锁阻塞。

对于以下代码,在main()中启动一个线程再中断它,由于线程中调用了Thread.sleep()方法,因此会抛出一个InterruptedException,从而提前结束线程,不执行之后的语句。

public class InterruptExample {

    private static class MyThread1 extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                System.out.println("Thread run");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public static void main(String[] args) throws InterruptedException {
    Thread thread1 = new MyThread1();
    thread1.start();
    thread1.interrupt();
    System.out.println("Main run");
}
Main run
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at InterruptExample.lambda$main$0(InterruptExample.java:5)
    at InterruptExample$$Lambda$1/713338599.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)

interrupted()

如果一个线程的run()方法执行了一个无限循环,并且没有执行sleep()等会抛出InterruptedException的操作,那么调用线程的interrupt()方法就无法使线程提前结束。

但是调用interrupt()方法会设置线程的中断标记,此时调用interrupted()方法会返回true。因此可以在循环体中使用interrupted()方法来判断线程是否处于中断状态,从而提前结束线程。

public class InterruptExample {

    private static class MyThread2 extends Thread {
        @Override
        public void run() {
            while (!interrupted()) {
                // ..
            }
            System.out.println("Thread end");
        }
    }
}
public static void main(String[] args) throws InterruptedException {
    Thread thread2 = new MyThread2();
    thread2.start();
    thread2.interrupt();
}
Thread end

Executor的中断操作

调用Executor的shutdown()方法会等待线程都执行完毕之后再关闭,但是如果调用的是shutdownNow()方法,则相当于调用了每个线程的interrupt()方法。

以下使用Lambda创建线程,相当于创建了一个匿名内部线程。

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> {
        try {
            Thread.sleep(2000);
            System.out.println("Thread run");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    executorService.shutdownNow();
    System.out.println("Main run");
}
Main run
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9)
    at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

如果只想中断Executor中的一个线程,可以通过使用submit()方法来提交一个线程,它会返回一个Future<?>对象,通过调用该对象的cancel(true)方法就可以中断线程。

Future<?> future = executorService.submit(() -> {
    // ..
});
future.cancel(true);

线程互斥同步

Java提供了两种锁机制来控制多个线程对共享资源的互斥访问,第一个是JVM实现的synchronized,另一个是JDK实现的ReentrantLock。

synchronized

  1. 同步一个代码块
public void func() {
    synchronized (this) {
        // ...
    }
}

它只作用于同一个对象,如果调用两个对象上的同步代码块,就不会进行同步。

对于以下代码,使用ExecuteService执行了两个线程,由于调用的是同一个对象的同步代码块,所以这两个线程会进行同步,当一个线程进入同步语句块时,另一个线程就必须等待。

public class SynchronizedExample {

    public void func1() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        }
    }
}
public static void main(String[] args) {
    SynchronizedExample e1 = new SynchronizedExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> e1.func1());
    executorService.execute(() -> e1.func1());
}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

对于以下代码,两个线程调用了不同对象的同步代码块,因此这两个线程就不需要同步。从输出结果可以看出,两个线程交叉执行。

public static void main(String[] args) {
    SynchronizedExample e1 = new SynchronizedExample();
    SynchronizedExample e2 = new SynchronizedExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> e1.func1());
    executorService.execute(() -> e2.func1());
}
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
  1. 同步一个方法
public synchronized void func () {
    // ...
}

它和同步代码块是一样的,作用于同一个对象。

  1. 同步一个类
public void func() {
    synchronized (SynchronizedExample.class) {
        // ...
    }
}

作用于整个类,也就是说这两个线程调用同一个类的不同对象上的这种同步语句,也会进行同步。

public class SynchronizedExample {

    public void func2() {
        synchronized (SynchronizedExample.class) {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        }
    }
}
public static void main(String[] args) {
    SynchronizedExample e1 = new SynchronizedExample();
    SynchronizedExample e2 = new SynchronizedExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> e1.func2());
    executorService.execute(() -> e2.func2());
}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
  1. 同步一个静态方法
public synchronized static void fun() {
    // ...
}

作用于整个类。

ReentrantLock

ReentrantLock是java.util.concurrent(J.U.C)包中的锁。

public class LockExample {

    private Lock lock = new ReentrantLock();

    public void func() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        } finally {
            lock.unlock(); // 确保释放锁,从而避免发生死锁。
        }
    }
}
public static void main(String[] args) {
    LockExample lockExample = new LockExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> lockExample.func());
    executorService.execute(() -> lockExample.func());
}
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

比较

1. 锁的实现

synchronized是JVM实现的,而ReentrantLock是JDK实现的。

2. 性能

新版本Java对synchronized进行了很多优化,例如自旋锁等,synchronized与ReentrantLock大致相同。

3.等待可中断

当持有锁等线程长期不释放锁等时候,正在等待的线程可以选择放弃等待,改为处理其他事情。

ReentrantLock可中断,而synchronized不行。

4. 公平锁

公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获取锁。

synchronized中的锁是非公平的,ReentrantLock默认情况下也是非公平的,但是也可以是公平的。

5. 锁绑定多个条件

一个ReentrantLock可以同时绑定多个Condition对象。

使用选择

除非需要使用ReentrantLock的高级功能,否则优先使用synchronized。这是因为synchronized是JVM实现的一种锁机制,JVM原生地支持它,而ReentrantLock不是所有JDK版本都支持。并且使用synchronized不用担心没有释放锁而导致死锁问题,因为JVM会确保锁的释放。

posted @ 2022-10-01 14:18  iiiiiiiivan  阅读(62)  评论(0)    收藏  举报