Android并发编程,其实还是关于Java层面的并发编程,在Android使用的各种开源库底层源码中,就涉及到Java的并发编程思想,所以对于Android开发来说,并发编程是一项非常重要的技术,这涉及到应用的性能问题。
1、多线程
先抛出一个常见的面试题:实现多线程的方式有几种?
这道题目的答案,在网络上什么答案都有,2种、4种甚至6种,实际在Oracle官网中已经明确给出了答案,2种!
(1)实现Runable接口;(2)继承Thread类
public class RunableStyle implements Runnable {
public static void main(String[] args){
Thread thread = new Thread(new RunableStyle());
thread.start();
}
@Override
public void run() {
System.out.println("这是Runable实现线程的方式");
}
}
public class ThreadStyle extends Thread {
@Override
public void run() {
System.out.println("这是继承Thread的方式实现多线程");
}
public static void main(String[] args){
new ThreadStyle().start();
}
}
以上是两种实现多线程的方式,这两种方法的本质区别就在于:
实现Runnable接口,其run方法会传入一个target对象(Runnable对象),执行target对象的run方法;
继承Thread类,是会重写run方法,不再有target,这些都被覆盖。
问题:如果这两种方式同时使用,会如何执行?
只会执行Thread的run方法,因为继承Thread类,会重写run方法,将Runnable的target全部覆盖。
2、启动线程
(1)start
和run
方法的区别
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread()+"");
}
};
runnable.run();
new Thread(runnable).start();
在执行run方法的时候,并没有开启新的线程,而是在主线程中执行的,而调用了start方法之后,就开启了一个新的线程。
因此start方法的含义:
—启动新的线程,但是并不决定线程执行的顺序;
—启动了两个线程:主线程 + 子线程
准备工作:
—线程处于就绪状态
(2)线程不能重复调用start方法的原因
当线程开始执行的时候,从就绪状态到执行状态,最终到终止状态,这个时候是不能再回到就绪状态的,因此不可以重复调用start方法,会抛出IllegalThreadStateException
异常。
Exception in thread "main" java.lang.IllegalThreadStateException
在调用start方法时,首先判断当前线程的状态threadStatus != 0,判断当前线程是不是初始化的状态,如果不是,就会抛出IllegalThreadStateException
异常,这也就时为什么不能连续调用线程的start方法的原因。
public sychronized void start(){
if(threadStatus != 0){
throw IllegalThreadStateException;
}
group.add(this);
xxxx
start0();
}
3、停止线程
(1)如何正确地停止线程?
使用interrupt通知,而不是强制,这是实际开发中,正确的停止线程的方式。
停止的场景分为以下几种:
—正常情况下,线程运行,没有wait或者sleep等阻塞情况的发生,去停止当前线程。
//打印10000的倍数
public static class NormalStopRunnable implements Runnable{
@Override
public void run() {
int num = 0;
while(num <= Integer.MAX_VALUE / 2){
if(num % 10000 == 0){
System.out.println(num+"是10000的倍数");
}
num++;
}
}
}
public static void main(String[] args) {
new Thread(new NormalStopRunnable()).start();
}
如果只是使用interrupt
来进行中断,是不能完成的,因此interrupt是作为通知,而不是强制的,也就是说运行的子线程是来决定是否终止线程的,因此以下这种方式是不会有效果的。
Thread thread = new Thread(new NormalStopRunnable());
thread.start();
//线程开始后1s中断
thread.sleep(1000);
thread.interrupt();
要在子线程中加一个判断标志!Thread.currentThread().isInterrupted()
,如果接收到中断的通知,就会中断当前的子线程。
public static class NormalStopRunnable implements Runnable{
@Override
public void run() {
int num = 0;
while( !Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 2){
if(num % 10000 == 0){
System.out.println(num+"是10000的倍数");
}
num++;
}
System.out.println("任务完成");
}
}
—阻塞的情况下
当子线程的任务执行完毕之后,设置线程处于休眠状态,这个时候来中断当前的线程。
public static class StopRunnableWithSleep implements Runnable{
@Override
public void run() {
int num = 0;
try {
while(num <= 300 && !Thread.currentThread().isInterrupted()){
if(num % 100 == 0){
System.out.println(num+"是100的倍数");
}
num++;
}
//执行完毕之后休眠
Thread.sleep(1000);
System.out.println("任务完成!");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new StopRunnableWithSleep());
thread.start();
// //线程开始后1s中断
thread.sleep(500);
thread.interrupt();
}
0是100的倍数
100是100的倍数
200是100的倍数
300是100的倍数
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at thread_core.stop.ThreadStop$StopRunnableWithSleep.run(ThreadStop.java:33)
at java.base/java.lang.Thread.run(Thread.java:834)
在没有阻塞的场景下,中断线程会响应中断的结果,但是在使用sleep的时候,会使用try-catch代码块,捕获InterruptedException
异常,也就是说,当前线程处于休眠状态的时候,执行interrupt
方法,就会被catch到InterruptedException
,sleep interrupted
,休眠被中断。
—循环迭代后的阻塞。
public static class StopRunnableWithSleepForLoop implements Runnable{
@Override
public void run() {
int num = 0;
try {
while(num <= 300){
if(num % 100 == 0){
System.out.println(num+"是100的倍数");
}
num++;
//每次循环结束都会阻塞
Thread.sleep(10);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new StopRunnableWithSleepForLoop());
thread.start();
// //线程开始后1s中断
thread.sleep(500);
thread.interrupt();
}
这种跟之前的不同之处在于,!Thread.currentThread().isInterrupted()
判断条件将不用再添加,因此每次阻塞中断都会抛出InterruptedException
异常,不需要再判断此时的条件。
关于while内try-catch的问题
public static class StopRunnableWithSleepForLoop implements Runnable{
@Override
public void run() {
int num = 0;
while(num <= 300){
if(num % 100 == 0){
System.out.println(num+"是100的倍数");
}
num++;
try {
//每次循环结束都会阻塞
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new StopRunnableWithSleepForLoop());
thread.start();
// //线程开始后1s中断
thread.sleep(500);
thread.interrupt();
}
如果try-catch没有将整个while循环包住,而是仅仅将sleep包住,那么就会出现下面的情况:虽然捕获了InterruptedException
,但是循环依然 执行下来了。
0是100的倍数
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at thread_core.stop.ThreadStop$StopRunnableWithSleepForLoop.run(ThreadStop.java:53)
at java.base/java.lang.Thread.run(Thread.java:834)
100是100的倍数
200是100的倍数
300是100的倍数
如果在while循环中,添加了while(num <= 300 && !Thread.currentThread().isInterrupted()){
判断中断的条件,还是没法中断的主要原因:
因为在捕获中断之后,Interrupted
标志位就会被清除,即便是加上了判断条件,其实是没用的,所以依然会执行下去。
那么可以在此基础上可以做改进,当Catch到InterruptedException
时,重新设置标志位,那么在后续的循环过程中,就会重新监测到中断标志位,这样就可以中断当前的线程。
public static class StopRunnableWithSleepForLoop implements Runnable{
@Override
public void run() {
int num = 0;
while(num <= 300 && !Thread.currentThread().isInterrupted()){
if(num % 100 == 0){
System.out.println(num+"是100的倍数");
}
num++;
try {
//每次循环结束都会阻塞
Thread.sleep(10);
}catch (InterruptedException e){
//在这里,恢复中断标志位!!!
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
}
0是100的倍数
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at thread_core.stop.ThreadStop$StopRunnableWithSleepForLoop.run(ThreadStop.java:53)
at java.base/java.lang.Thread.run(Thread.java:834)
Process finished with exit code 0
4、线程的生命周期
先把线程生命周期的6个状态列出来:
New、Runnable、Blocked、Waiting、Timed Waiting、Terminated
(1)New:新建状态,就是通过new Thread创建新的线程,但是还没有调用start方法;
(2)Runnable:运行状态,当调用start方法之后,线程开始运行时,就是Runnable
状态,但是调用了start方法并不一定是进入运行状态。
(3)Blocked:阻塞状态;当使用sychronized代码修饰,部分线程没有获取线程锁的时候,就进入阻塞状态。
(4)Waiting:等待状态;调用了wait方法、join方法或者LockSupport.park(),就会进入等待状态。
(5)Timed Waiting:计时等待状态,和Waiting不同之处在于,这个是有参数的,而且在时间到时之后,会被自动唤醒,Waiting只能notify唤醒。
(6)Terminated:执行完成。
Thread thread = new Thread(new ThreadStatusRunnable());
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.getState());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//执行完毕之后
System.out.println(thread.getState());
NEW
RUNNABLE
RUNNABLE
TERMINATED