线程的创建

java创建线程有两种方法

创建Thread的子类

1
2
3
4
5
6
7
    public class MyThread extends Thread {
    public void run(){
    System.out.println("MyThread running");
    }
    }
    ​MyThread myThread = new MyThread();
    myTread.start();

实现Runnable接口

1
2
3
4
5
6
7
    public class MyRunnable implements Runnable {
    public void run(){
    System.out.println("MyRunnable running");
    }
    }
    Thread thread = new Thread(new MyRunnable());
    thread.start();

Thread和Runable的区别

Thread 继承了Runnable接口,提供了一系列 线程方法与属性跟踪

线程名称

1
2
3
    创建线程的时候可以给线程起一个名字,用来区分不同的线程
    Thread的子类通过getName方法获取
    实现runnable接口的通过Thread.currentThread().getName()获取

线程的优先级

  1. 当线程的优先级没有指定时,所有线程都携带普通优先级。
  2. 优先级可以用从1到10的范围指定。10表示最高优先级,1表示最低优先级,5是普通优先级。
  3. 优先级最高的线程在执行时被给予优先。但是不能保证线程在启动时就进入运行状态。
  4. 与在线程池中等待运行机会的线程相比,当前正在运行的线程可能总是拥有更高的优先级。
  5. 由调度程序决定哪一个线程被执行。
  6. t.setPriority()用来设定线程的优先级。
  7. 在线程开始方法被调用之前,线程的优先级应该被设定。
  8. 你可以使用常量,如MIN_PRIORITY,MAX_PRIORITY,NORM_PRIORITY来设定优先级

线程的执行

使用start方法启动线程

start和run方法的区别

start才是进入子线程执行,直接调用run方法的话和普通方法没有差别

线程的执行顺序

启动线程的顺序是有序的,但是执行的顺序是无序的

挂起/睡眠线程

线程的挂起实际上是线程进入非执行状态,在这个阶段CPU不会分给线程时间片

sleep方法

使线程暂时停止一段时间,在哪个线程中调用就哪个线程暂停

1
2
3
4
5
6
      public static void main(String[] args)throws InterruptedException {
            ThreadA ta = new ThreadA();
            ta.start();
            ta.sleep(5000);
            System.out.println("TestNew is running");
        }

可以看到主线程暂停了5秒而不是ThreadA暂停了5秒

对锁的处理: 该方法不会释放锁

join方法

使当前线程停下来等待,直到调用join方法的线程结束再恢复执行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    Thread thread1=new Thread(new Runnable() {
                @Override
                public void run() {
                    //模拟阻塞状态
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread1.start();
            try {
                thread1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("end");

可以看到主线程等待了10秒才输出最后的end

对锁的处理: 该方法不会释放锁

wait方法

使该线程挂起

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    Thread thread1=new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (lock){
                        System.out.println("线程1开始运行");
                        //模拟阻塞状态
                        try {
                            lock.wait();
                            TimeUnit.SECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("线程1结束运行");
                    }

                }
            });
            Thread thread2=new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (lock){
                        System.out.println("线程2开始运行");
                        //模拟阻塞状态
                        try {
                            TimeUnit.SECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("线程2运行结束");
                        lock.notify();
                    }
                }
            });
            thread1.start();
            thread2.start();
            try {
                thread1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("end");

运行结果

1
2
3
4
5
    线程1开始运行
    线程2开始运行
    线程2运行结束
    线程1结束运行
    end

对锁的处理: 调用wait的线程会释放锁

yield

暂停当前正在执行的线程对象,并执行其他线程

一个调用yield()方法的线程告诉虚拟机它乐意让其他线程占用自己的位置。这表明该线程没有在做一些紧急的事情

注意:该方法并不保证产生效果

例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程1开始运行");
                    for(int i=0;i<5;i++){
                        System.out.println(i);
                        Thread.yield();
                    }
                    System.out.println("线程1结束");
                }
            });
            Thread thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程2开始运行");
                    for(int i=0;i<5;i++){
                        System.out.println(i);
                        Thread.yield();
                    }
                    System.out.println("线程2结束");
                }
            });
            thread1.start();
            thread2.start();

输出

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    线程1开始运行
    0
    线程2开始运行
    0
    1
    1
    2
    2
    3
    3
    4
    4
    线程1结束
    线程2结束

可以看到线程1和线程2交替执行

没有使用yield时

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    线程1开始运行
    0
    1
    2
    3
    4
    线程1结束
    end
    线程2开始运行
    0
    1
    2
    3
    4
    线程2结束

对锁的处理: 不会释放锁

和join的区别

  1. 它仅能使一个线程从运行状态转到可运行状态,而不是等待或者阻塞状态
  2. 它是Thread的静态方法

恢复线程

  • 从sleep中恢复

等待时间结束,线程自动恢复

  • 从join中恢复

指定线程执行完成,或者等待超时

  • 从wait中恢复

另一个线程调用=notify=方法,或者等待超时

  • 通用方法

使用 interrupt 强行打断,并捕获异常

中断线程

  • 使用Thead中的stop方法(不推荐)
  • 使用Thread中的interrupt方法
  • 自定义中断信号量
  • 使用 java.util.concurrent 并发包下面提供的方法(很多实质还是 interrupt()),譬如 Future 的 boolean cancel(boolean mayInterruptIfRunning) 方法、ExecutorService 的 shutdown()、shutdownNow() 方法等

interrupt方法

为目标线程*设置一个标志*,标识它已经被中断,并抛出异常

注意如果只是调用interrupt方法,线程并没有实际中断,之后的代码会继续执行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
      Thread thread1=new Thread(new Runnable() {
                @Override
                public void run() {
                    //模拟阻塞状态
                    try {
                        TimeUnit.SECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        // e.printStackTrace();
                        return;
                    }
                }
            });
            thread1.start();
            thread1.interrupt();

运行上面的代码可以发现线程很快就被中断了

待决中断

在线程阻塞之前调用interrupt方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
    Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程1开始运行");
                    Thread.currentThread().interrupt();
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        return;
                    }
                    System.out.println("线程1结束运行");

                }
            });
            thread1.start();
            System.out.println("end");

可以看到线程一运行到sleep就退出了

interrupt中断状态校验

可以在Thread对象上调用isInterrupted()方法来检查任何线程的中断状态。这里需要注意:线程一旦被中断(调用interrupted方法),isInterrupted()方法便会返回true,而一旦抛出=InterruptedException=异常,它将清空中断标志,此时isInterrupted()方法将返回false

isInterrupted和interrupted的区别

查看源码可以看到这两个方法都调用了=native boolean isInterrupted= 区别在于传递的参数不同,看源码的注释

1
2
3
4
5
6
     /**
         * Tests if some Thread has been interrupted.  The interrupted state
         * is reset or not based on the value of ClearInterrupted that is
         * passed.
         */
        private native boolean isInterrupted(boolean ClearInterrupted);

意思就是是否清除中断标识,=isInterrupted=不会清除标识,而=interrupted=会清除标识,在待决中断中会使中断失效

使用限制

对于下面这样的线程interrupt是无法将其中断的

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程1开始运行");
                    while (true) {
                        System.out.println("----");
                    }
                }
            });
            thread1.start();
            thread1.interrupt();
            System.out.println("end");

需要将循环条件修改为=!Thread.currentThread().isInterrupted()=

参考资料

【Java并发编程】之二:线程中断

自定义中断信号量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    private volatile static boolean isStop=false;

        public static void main(String[] args)  {
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程1开始运行");
                    while (!isStop) {
                        System.out.println("循环");
                        try {
                            TimeUnit.SECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程1结束运行");

                }
            });
            thread1.start();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            isStop=true;
            System.out.println("end");
        }

在运行一个循环后线程结束运行

关于Java 代码中停止线程方法相关的经验基础题

线程生命周期

线程状态

Java线程在某个时刻只能处于以下六个状态中的一个

1
2
3
4
5
6
7
8
    public enum State {
            NEW,
            RUNNABLE,
            BLOCKED,
            WAITING,
            TIMED_WAITING,
            TERMINATED;
        }
  • 新创建(new)

    一个线程被创建出来还没有调用start方法

  • 可运行(Runnable)

    可在jvm运行的状态,一个可运行的线程可能正在运行自己的代码也可能没有,这取决于操作系统提供的时间片

  • 被阻塞(Blocked)

    当一个线程试图获取一个内部的对象锁,而该锁此时正在被其它线程持有时,则进入阻塞状态

  • 等待(wait)

当线程等待另一个线程通知调度器一个条件时,它直接进入等待状态.在调用Object.wait方法或Thread.join方法,或者是等待java.util.concurrent库中的Lock或Condition时,就会出现这种情况

  • 计时等待(Timed waiting) Object.wait、Thread.join、Lock.tryLock和Condition.await等方法有超时参数,还有Thread.sleep方法、LockSupport.parkNanos方法和LockSupport.parkUntil方法,这些方法会导致线程进入计时等待状态,如果超时或者出现通知,都会切换会可运行状态

  • 被终止(Terminated)

    因为run方法正常退出而死亡,或者因为没有捕获的异常终止了run方法而死亡