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 不改变线程的状态, 但是会重新去排队,⽽排队之后选择谁是不确定的
 

### Java 线程基础教程 #### 1. 理解线程的概念 在计算机科学中,线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,多个线程可以在同一时间内并发执行[^2]。 #### 2. 创建线程的方法 Java 提供了两种创建线程的方式:继承 `Thread` 和实现 `Runnable` 接口。这两种方式都允许开发者定义线程的行为逻辑,并启动新的线程来执行特定的任务。 - **通过继承 Thread ** ```java class MyThread extends Thread { public void run() { System.out.println("这是一个新线程"); } } public class Main { public static void main(String[] args) { new MyThread().start(); } } ``` - **通过实现 Runnable 接口** ```java class MyRunnable implements Runnable { @Override public void run() { System.out.println("这是另一个新线程"); } } public class Main { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); } } ``` #### 3. 同步机制的重要性 当多个线程访问共享资源时可能会发生数据竞争条件,因此需要同步机制来确保线程安全。可以使用关键字 `synchronized` 来声明方法或代码块为同步区域,在任何时刻只允许一个线程进入该区域操作共享变量。 ```java public synchronized void incrementCounter(){ counter++; } ``` #### 4. 使用现代工具简化编程模型 除了传统的线程管理外,还可以利用更高层次抽象如 ExecutorService 和 ForkJoinPool 这样的库函数来进行更高效的异步任务处理。 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; ExecutorService executor = Executors.newFixedThreadPool(5); for (int i=0; i<10 ;i++){ executor.submit(() ->{ try { // 执行某些耗时的操作... } catch(Exception e){ e.printStackTrace(); } }); } executor.shutdown(); ``` 以上介绍了有关于 Java 多线程的一些基础知识以及如何简单地应用这些概念编写多线程程序。对于初学者来说,掌握好上述内容已经足以应对大多数日常开发需求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值