本次我将经过两篇文章进行分享。第二篇传送门JAVA并发不会?怎么办,看这里(二)html
有三种使用线程的方法:java
接口的类只能当作一个能够在线程中运行的任务,不是真正意义上的线程,所以最后还须要经过 Thread 来调用。能够理解为任务是经过线程驱动从而执行的。git
须要实现接口中的 run() 方法。程序员
public class MyRunnable implements Runnable {
@Override
public void run() {
// ...
}
}
复制代码
使用 Runnable 实例再建立一个 Thread 实例,而后调用 Thread 实例的 start() 方法来启动线程。github
public static void main(String[] args) {
MyRunnable instance = new MyRunnable();
Thread thread = new Thread(instance);
thread.start();
}
复制代码
与 Runnable 相比,Callable 能够有返回值,返回值经过 FutureTask 进行封装。bash
public class MyCallable implements Callable<Integer> {
public Integer call() {
return 123;
}
}
复制代码
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable mc = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(mc);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
复制代码
一样也是须要实现 run() 方法,由于 Thread 类也实现了 Runable 接口。并发
当调用 start() 方法启动一个线程时,虚拟机会将该线程放入就绪队列中等待被调度,当一个线程被调度时会执行该线程的 run() 方法。oracle
public class MyThread extends Thread {
public void run() {
// ...
}
}
复制代码
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
复制代码
实现接口会更好一些,由于:框架
Executor 管理多个异步任务的执行,而无需程序员显式地管理线程的生命周期。这里的异步是指多个任务的执行互不干扰,不须要进行同步操做。异步
主要有三种 Executor:
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
executorService.execute(new MyRunnable());
}
executorService.shutdown();
}
复制代码
守护线程是程序运行时在后台提供服务的线程,不属于程序中不可或缺的部分。
当全部非守护线程结束时,程序也就终止,同时会杀死全部守护线程。
main() 属于非守护线程。
在线程启动以前使用 setDaemon() 方法能够将一个线程设置为守护线程。
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true);
}
复制代码
Thread.sleep(millisec) 方法会休眠当前正在执行的线程,millisec 单位为毫秒。
sleep() 可能会抛出 InterruptedException,由于异常不能跨线程传播回 main() 中,所以必须在本地进行处理。线程中抛出的其它异常也一样须要在本地进行处理。
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
复制代码
对静态方法 Thread.yield() 的调用声明了当前线程已经完成了生命周期中最重要的部分,能够切换给其它线程来执行。该方法只是对线程调度器的一个建议,并且也只是建议具备相同优先级的其它线程能够运行。
public void run() {
Thread.yield();
}
``
`
## 中断
一个线程执行完毕以后会自动结束,若是在运行过程当中发生异常也会提早结束。
### InterruptedException
经过调用一个线程的 interrupt() 来中断该线程,若是该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 InterruptedException,从而提早结束该线程。可是不能中断 I/O 阻塞和 synchronized 锁阻塞。
对于如下代码,在 main() 中启动一个线程以后再中断它,因为线程中调用了 Thread.sleep() 方法,所以会抛出一个 InterruptedException,从而提早结束线程,不执行以后的语句。
```java
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)
复制代码
若是一个线程的 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();
}
复制代码
调用 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。
public void func() {
synchronized (this) {
// ...
}
}
复制代码
它只做用于同一个对象,若是调用两个对象上的同步代码块,就不会进行同步。
对于如下代码,使用 ExecutorService 执行了两个线程,因为调用的是同一个对象的同步代码块,所以这两个线程会进行同步,当一个线程进入同步语句块时,另外一个线程就必须等待。
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
复制代码
public synchronized void func () {
// ...
}
复制代码
它和同步代码块同样,做用于同一个对象。
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
复制代码
public synchronized static void fun() {
// ...
}
复制代码
做用于整个类。
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
复制代码
synchronized 是 JVM 实现的,而 ReentrantLock 是 JDK 实现的。
新版本 Java 对 synchronized 进行了不少优化,例如自旋锁等,synchronized 与 ReentrantLock 大体相同。
当持有锁的线程长期不释放锁的时候,正在等待的线程能够选择放弃等待,改成处理其余事情。
ReentrantLock 可中断,而 synchronized 不行。
公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次得到锁。
synchronized 中的锁是非公平的,ReentrantLock 默认状况下也是非公平的,可是也能够是公平的
一个 ReentrantLock 能够同时绑定多个 Condition 对象。
除非须要使用 ReentrantLock 的高级功能,不然优先使用 synchronized。这是由于 synchronized 是 JVM 实现的一种锁机制,JVM 原生地支持它,而 ReentrantLock 不是全部的 JDK 版本都支持。而且使用 synchronized 不用担忧没有释放锁而致使死锁问题,由于 JVM 会确保锁的释放。
当多个线程能够一块儿工做去解决某个问题时,若是某些部分必须在其它部分以前完成,那么就须要对线程进行协调。
在线程中调用另外一个线程的 join() 方法,会将当前线程挂起,而不是忙等待,直到目标线程结束。
对于如下代码,虽然 b 线程先启动,可是由于在 b 线程中调用了 a 线程的 join() 方法,b 线程会等待 a 线程结束才继续执行,所以最后可以保证 a 线程的输出先于 b 线程的输出。
public class JoinExample {
private class A extends Thread {
@Override
public void run() {
System.out.println("A");
}
}
private class B extends Thread {
private A a;
B(A a) {
this.a = a;
}
@Override
public void run() {
try {
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}
}
public void test() {
A a = new A();
B b = new B(a);
b.start();
a.start();
}
}
复制代码
public static void main(String[] args) {
JoinExample example = new JoinExample();
example.test();
}
复制代码
A
B
复制代码
调用 wait() 使得线程等待某个条件知足,线程在等待时会被挂起,当其余线程的运行使得这个条件知足时,其它线程会调用 notify() 或者 notifyAll() 来唤醒挂起的线程。
它们都属于 Object 的一部分,而不属于 Thread。
只能用在同步方法或者同步控制块中使用,不然会在运行时抛出 IllegalMonitorStateException。
使用 wait() 挂起期间,线程会释放锁。这是由于,若是没有释放锁,那么其它线程就没法进入对象的同步方法或者同步控制块中,那么就没法执行 notify() 或者 notifyAll() 来唤醒挂起的线程,形成死锁。
public class WaitNotifyExample {
public synchronized void before() {
System.out.println("before");
notifyAll();
}
public synchronized void after() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after");
}
}
复制代码
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
WaitNotifyExample example = new WaitNotifyExample();
executorService.execute(() -> example.after());
executorService.execute(() -> example.before());
}
复制代码
before
after
复制代码
wait() 和 sleep() 的区别
java.util.concurrent 类库中提供了 Condition 类来实现线程之间的协调,能够在 Condition 上调用 await() 方法使线程等待,其它线程调用 signal() 或 signalAll() 方法唤醒等待的线程。
相比于 wait() 这种等待方式,await() 能够指定等待的条件,所以更加灵活。
使用 Lock 来获取一个 Condition 对象。
public class AwaitSignalExample {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void before() {
lock.lock();
try {
System.out.println("before");
condition.signalAll();
} finally {
lock.unlock();
}
}
public void after() {
lock.lock();
try {
condition.await();
System.out.println("after");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
复制代码
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
AwaitSignalExample example = new AwaitSignalExample();
executorService.execute(() -> example.after());
executorService.execute(() -> example.before());
}
复制代码
before
after
复制代码
一个线程只能处于一种状态,而且这里的线程状态特指 Java 虚拟机的线程状态,不能反映线程在特定操做系统下的状态。
建立后还没有启动。
正在 Java 虚拟机中运行。可是在操做系统层面,它可能处于运行状态,也可能等待资源调度(例如处理器资源),资源调度完成就进入运行状态。因此该状态的可运行是指能够被运行,具体有没有运行要看底层操做系统的资源调度。
请求获取 monitor lock 从而进入 synchronized 函数或者代码块,可是其它线程已经占用了该 monitor lock,因此出于阻塞状态。要结束该状态进入从而 RUNABLE 须要其余线程释放 monitor lock。
等待其它线程显式地唤醒。
阻塞和等待的区别在于,阻塞是被动的,它是在等待获取 monitor lock。而等待是主动的,经过调用 Object.wait() 等方法进入。
无需等待其它线程显式地唤醒,在必定时间以后会被系统自动唤醒。
调用 Thread.sleep() 方法使线程进入限期等待状态时,经常用“使一个线程睡眠”进行描述。调用 Object.wait() 方法使线程进入限期等待或者无限期等待时,经常用“挂起一个线程”进行描述。睡眠和挂起是用来描述行为,而阻塞和等待用来描述状态。
能够是线程结束任务以后本身结束,或者产生了异常而结束。
本文参考聊聊并发(八)——Fork/Join 框架介绍、线程通讯、Threads and Locks、Threads and Locks、CS-Notes、Java内存模型 之三个特性、轻量级锁、thread state java
第二篇传送门JAVA并发不会?怎么办,看这里(二)