Thread 类的基本用法(附详细代码),通俗易懂。

目录

1、线程创建

2、线程中断

3、线程等待

4、线程休眠

5、获取线程实例

6、yield让出执行权


1、线程创建

1.1 继承Thread类

/**
 * 继承Thread创建线程
 */
public class ThreadDemo3 {
    public static void main(String[] args) {
        //获得当前线程
        Thread mainThread = Thread.currentThread();
        System.out.println("线程名称" + mainThread.getName());

        Thread thread = new MyThread();
        //开启线程
        thread.start();
    }
}

class MyThread extends Thread{
    @Override
    public void run() {
        //具体的业务执行代码
        Thread thread = Thread.currentThread();
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        System.out.println( "线程的名称"+ thread.getName());
    }
}

1.2 实现Runnable接口

/**
 * 实现Runnable接口线程
 */

public class ThreadDemo4 {
    public static void main(String[] args) {
        //创建Runnable
        MyThread2 myThread2 = new MyThread2();
        //创建一个线程
        Thread thread = new Thread(myThread2);
        //启动线程
        thread.start();
    }
}
class MyThread2 implements Runnable{
    @Override
    public void run() {
        //具体的业务代码
        Thread thread = Thread.currentThread();//得到当前线程
        System.out.println("线程执行:" + thread.getName());
    }
}

1.3 匿名内部类

/**
 * 匿名内部类
 */
public class ThreadDemo5 {
    public static void main(String[] args) {
        //创建一个线程
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //业务代码
                Thread t = Thread.currentThread();
                System.out.println("执行任务" + t.getName());
            }
        });
        //启动线程
        thread.start();
    }
}

1.4 使用lambda来创建Runnable

 * 使用lambda来创建Runnable
 */
public class ThreadDemo6 {
    public static void main(String[] args) {
        //创建线程
        Thread thread = new Thread(()->{
            //具体的业务
            Thread t = Thread.currentThread();
            System.out.println("任务执行:" + t.getName());
        });
        //启动线程
        thread.start();
    }
}

创建线程小结:

创建线程有 3 ⼤类实现⽅式、7 种实现⽅法,如果是 JDK 1.8 以上版本,在不需要获得线程执⾏结果的
情况下,推荐使⽤ Lambda ⽅式来创建线程,因为它的写法⾜够简洁;如果想要获取线程执⾏结果,可
使⽤ FutureTask + Callable 的⽅式来实现。
 

2、线程中断

2.1:使用自定义标识符来终止线程

public class ThreadInterrupet {
    //1.声明一个自定义标识符
    private volatile static boolean flag = false;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            while (!flag){
                System.out.println("正在转账...");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("差点误了大事");
        });
        thread.start();

        Thread.sleep(3000);
        //终止线程
        System.out.println("停止交易");
        flag = true;
    }
}

2.2:使用 interrupt() 终止线程

使⽤ Thread.interrupted() 或者 Thread.currentThread().isInterrupted() 代替⾃定义标志位

使⽤ thread 对象的 interrupted() ⽅法通知线程结束
 

 

public class ThreadInterrupet2 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
           while (!Thread.interrupted()){//两种方式皆可
 //           while (!Thread.currentThread().isInterrupted()){
                System.out.println("正在转账...");
            }
            System.out.println("差点误了大事");
        });
        thread.start();
        Thread.sleep(100);
        //终止线程
        thread.interrupt();
        System.out.println("终止交易");

    }

}

isInterrupted VS interrupted

interrupted:判断当前线程的中断标志位是否设置,调⽤后清除标志位。
isInterrupted:判断对象关联的线程的标志位是否设置,调⽤后不清除标志位

public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) { }
            System.out.println("isInterrupted:" +
Thread.currentThread().isInterrupted());
            System.out.println("isInterrupted:" +
Thread.currentThread().isInterrupted());
            System.out.println("isInterrupted:" +
Thread.currentThread().isInterrupted());
            System.out.println();
            System.out.println("interrupted:" + Thread.interrupted());
            System.out.println("interrupted:" + Thread.interrupted());
            System.out.println("interrupted:" + Thread.interrupted());
       }
   });
    t.start();
    Thread.sleep(100);
    t.interrupt();
  }


 

3、线程等待

3.1 join用法

 

public class ThreadByJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
          //1.张三上班
            System.out.println("1.张三开始上班");
          //2.张三正在上班
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //3.张三下班
            System.out.println("3.张三下班");
        });
        t1.start();

//        while (t1.isAlive()){
//
//        }

        t1.join();


        Thread t2 = new Thread(()->{
           //1.李四开始上班
            System.out.println("1.李四开始上班");

           //2.李四正在上班
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //3.李四下班
            System.out.println("3.李四下班");
        });
        t2.start();
    }
}

4、线程休眠

4.1 sleep休眠

 

public class ThreadSleep {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            try {
                Thread.sleep(60 * 60 * 1000);
            } catch (InterruptedException e) {
//                e.printStackTrace();
                System.out.println("我接到了一个终止执行的通知");
            }
        });
        thread.start();
        Thread.sleep(1000);
        System.out.println("终止子线程thread");
        thread.interrupt();
    }
}

4.2 TimeUtil休眠

 

public class ThreadTimeUtil {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("主线程开始执行了:" + LocalTime.now());
        TimeUnit.SECONDS.sleep(3);
        System.out.println("主线程又开始执行了" + LocalTime.now());
    }

}

5、获取线程实例

 

public class ThreadDemoGet {
    public static void main(String[] args) {
        Thread thread = MyThread.currentThread();
        System.out.println("获取到线程实例" + thread.getName());
    }
}

6、yield让出执行权

public class ThreadYield {
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            //得到当前线程
            Thread cThread = Thread.currentThread();
            for (int i = 0; i < 100; i++) {
                //让出CPU执行权
                Thread.yield();
                System.out.println("执行线程:" + cThread.getName());
            } 
        },"张三");

        t1.start();

        new Thread(()->{
            Thread cThread = Thread.currentThread();
            for (int i = 0; i < 100; i++) {
                System.out.println("执行线程:" + cThread.getName());
            }
        },"李四").start();
    }
}

运行后可以看到:
1. 不使⽤ yield 的时候, 张三李四⼤概五五开
2. 使⽤ yield 时, 张三的数量远远少于李四
结论:
yield 不改变线程的状态, 但是会重新去排队,⽽排队之后选择谁是不确定的
 

  • 13
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值