目录

Thread类

Java创建线程的方式

Java有两种创建线程的方式,继承Thread类或实现Runnable接口。

案例代码:

 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
42
43
44
45
46
47
48
49
50
51
52
/**
 * 开启线程的两种方式:
 * 1.继承Thread类。
 * 2.实现Runnable接口。
 */
public class ThreadDemo {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("----------");
        System.out.println("继承Thread类开启线程");
        MyThread t1 = new MyThread();
        t1.start();

        Thread.sleep(100);

        System.out.println("----------");
        System.out.println("实现Runnable接口开启线程");
        MyRunnable myRunnable = new MyRunnable();
        Thread t2 = new Thread(myRunnable);
        t2.start();

        Thread.sleep(100);

        System.out.println("----------");
        System.out.println("继承Thread类,并实现Runnable接口时,继承类方法生效");
        MyRunnable r2 = new MyRunnable();
        Thread t3 = new MyThread(r2);
        t3.start();
    }

    static class MyRunnable implements Runnable {

        @Override
        public void run() {
            System.out.println("实现Runnable接口。");
        }
    }

    static class MyThread extends Thread {
        public MyThread() {
        }

        public MyThread(Runnable target) {
            super(target);
        }

        @Override
        public void run() {
            System.out.println("继承Thread类。");
        }
    }
}

常用方法特点

静态方法

  • yield():试着让出cpu周期,不释放锁
  • sleep():线程休眠一段时间,不释放锁
  • currentThread():获取当前线程
  • interrupted():重置当前线程的中断状态

非静态方法

  • start():创建新的线程
  • run():执行run方法在当前线程
  • setName():设置线程的名字
  • join():等待其子线程执行完毕
  • setDaemon():参数为true则设置线程为守护线程
  • interrupt():尝试中断线程,取消任务时使用
  • isInterrupted():线程是否中断

注意

  • 每个线程对象只能调用一次start()方法
  • setName、setDaemon方法若调用则在start方法前调用
  • 线程只是start方法比较特殊,继承跟实现规则与普通类没有区别。因此在实现Thread、Runnable时,子类可定义任意的属性及方法