Thread 类的基本用法

文章详细介绍了Java中线程的创建,包括继承Thread类、实现Runnable接口以及使用lambda表达式的方式。同时,讨论了线程中断的方法,如使用自定义标志位和Thread的内置中断机制。此外,还提到了线程等待(join方法)和线程休眠(sleep方法)的使用,以及如何获取线程实例。

目录

一、线程的创建

1、继承Thread类,重写run方法

📝方式一、正常写法

📝方式二、使用匿名内部类

 2、实现 Runnable, 重写 run方法

📝方式一:正常写法

 📝方式二、使用匿名内部类

3、使用 lambda 表达式

二、线程中断

1、使用自己的标志位来区分线程是否要结束

  2、使用Thread自带的标志位

三、线程等待 

四、线程休眠 

五、获取线程实例


一、线程的创建

1、继承Thread类,重写run方法

📝方式一、正常写法

  1. 创建一个继承于Thread类的子类并在该子类中重写run方法
  2. 实例化该子类,用父类Thread引用重写了run方法的子类对象
  3. 调用start方法,创建该线程.
class MyThread1 extends Thread{
    public void run(){
        System.out.println("hello t");
    }
}
public class ThreadDemo1 {
    public static void main(String[] args) {
        Thread t=new MyThread1();
        t.start();
        System.out.println("hello main");
    }
}

📝方式二、使用匿名内部类

 跟上述的一样,只不过用的手段不同

public class ThreadDemo3 {
    public static void main(String[] args) {
        Thread t=new Thread(){
            public void run(){//匿名内部类
                    System.out.println("hello t");
                }
        };
        t.start();
            System.out.println("hello main");
    }
}

 2、实现 Runnable, 重写 run方法

📝方式一:正常写法

1.创建一个实现了Runnable接口的类并用该类去实现Runnable中的抽象方法:run方法
2.创建实现类的对象,将此对象作为参数传递给Thread,创建Thread类的对象
3.调用start方法,创建线程

class MyThread2 implements Runnable{
    @Override
    public void run() {
        while(true){
            System.out.println("hello t");
        }
    }
}
public class threadDemo2 {
    public static void main(String[] args) {
        MyThread2 myThread2=new MyThread2();
        Thread t=new Thread(myThread2);
        t.start();
        while(true){
            System.out.println("hello main");
        }
    }
}

 📝方式二、使用匿名内部类

public class ThreadDemo4 {
    public static void main(String[] args) {
        Thread t=new Thread(new Runnable(){//匿名内部类
            public void run(){
                while(true){
                    System.out.println("hello t");
                }
            }
        });
        t.start();
        while(true){
            System.out.println("hello main");
        }
    }
}

3、使用 lambda 表达式

推荐使用lambda来创建线程

public class ThreadDemo5 {
    public static void main(String[] args) {
        Thread t=new Thread(()->{//lambda表达式
                while(true) {
                    System.out.println("hello t");
                }
        });
        t.start();
        while(true){
            System.out.println("hello main");
        }
    }
}

二、线程中断

1、使用自己的标志位来区分线程是否要结束

使一个线程结束,就让这个线程的run方法执行完就可以了.所以,我们可以创建一个可以影响线程A结束的标志位,让另一个线程B来控制这个标志位从而控制线程A的结束,因为同一个进程下的线程共用一块空间,所以线程A改变结束标志位就可以影响到线程B.

public class Demo10 {
    // 这个变量就是线程 t 的结束标志位
    private static boolean isQuit = false;
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (!isQuit) {//这个变量控制着这个线程的是否结束
                System.out.println("hello t");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        isQuit = true;        // main 线程修改 isQuit 的值使线程t结束.
    }
}

  2、使用Thread自带的标志位

使用 Thread.interrupted() 或者 Thread.currentThread().isInterrupted() 代替自定
义标志位. Thread 内部包含了一个 boolean 类型的变量作为线程是否被中断的标记.
public class ThreadDemo7 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while(!Thread.interrupted())//Thread.currentThread().isInterrupted()
            {
                System.out.println("hello");
            }
        });
        t.start();
        Thread.sleep(500);
        t.interrupt();
    }
}

三、线程等待 

使用join方法来使线程等待,main方法会等t1和t2执行完才执行

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Thread t1=new Thread(()->{
            System.out.println("1");
        });
        Thread t2=new Thread(()->{
            System.out.println("2");
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("3");
    }
}

四、线程休眠 

sleep方法会使线程休眠一段时间

public static void sleep(long millis) throws InterruptedException 线程休眠millis毫秒

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(System.currentTimeMillis());
        Thread.sleep(3 * 1000);
        System.out.println(System.currentTimeMillis());
   }
}

五、获取线程实例

1.继承Thread,重写run方法,可以直接在run方法中使用this即可获取线程实例

//继承Thread,使用this
class MyThread1 extends Thread{
    public void run(){
        System.out.println(this);
    }
}
public class ThreadDemo1 {
    public static void main(String[] args) {
        Thread t=new MyThread1();
        t.start();
    }
}

2.实现Runna,重写run方法或者使用lambda表达式,this就用不了了,应该使用

Thread.currentThread()方法,哪个线程调用的就获取哪个线程的实例.

//实现Runnable,使用Thread.currentThread()
class MyThread2 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread());

    }
}
public class threadDemo2 {
    public static void main(String[] args) {
        MyThread2 myThread2=new MyThread2();
        Thread t=new Thread(myThread2);
        t.start();
        System.out.println(Thread.currentThread());
    }
}

lambda表达式 

//lambda表达式,用Thread.currentThread()
public class ThreadDemo5 {
    public static void main(String[] args) {
        Thread t=new Thread(()->{
                    System.out.println(Thread.currentThread());

        });
        t.start();
        System.out.println(Thread.currentThread());
    }
}

上面所有的运行结果均为: 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值