创建线程的方法

这篇博客详细介绍了在Java中创建线程的几种方法,包括继承Thread类和实现Runnable接口,同时提到了Thread.currentThread()用于获取当前线程引用的重要性。此外,还讨论了使用匿名类和Lambda表达式创建线程对象的实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建线程的方法

1.继承Thread类来创建线程,这个方法的好处是this代表的就是当前线程,不需要通过Thread.currentThread()来获取当前线程的引用。

public class main {
    public  static class myThread extends Thread{
        @Override
        public void run() {
            System.out.println("创建出来的线程");
        }
    }
    public static void main(String[] args) {
        myThread t1=new myThread();
        t1.start();
    }
}

2.实现Runnable接口,并且调用Thread的构造方法时将Runnable对象作为target参数传入来创建线程对象,好处是可以规避类的单继承限制,但需要通过Thread.currentThread()来获取当前线程的引用。

public class main {
    public static class MyRunnbale implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"通过Runnable创建出来的线程");
        }
    }
    public static void main(String[] args) {
        Thread t1=new Thread(new MyRunnbale());
        t1.start();
    }
}

Thread.currentThread()可以获取当前线程的引用。

使用匿名类创建Thread对象

使用匿名类创建Runnable子类对象

使用Lambda表达式创建Runnable子类对象

Thread的常见属性

public class ThreadFields {
    public static void main(String[] args) {
        //Thread.currentThread()
        //获取当前线程Thread对象
        Thread currentThread=Thread.currentThread();
        System.out.println(currentThread.getName());//获取名称
        System.out.println(currentThread.getId());//获取Id
        System.out.println(currentThread.getPriority());//优先级
        System.out.println(currentThread.getState());//状态
        System.out.println(currentThread.isDaemon());//是否是后台线程
        System.out.println(currentThread.isAlive());//是否存活
        System.out.println(currentThread.isInterrupted());//是否被中断
    }
}
/*
执行结果:
main
1
5
RUNNABLE
false
true
false
*/

Thread的常见构造方法

public class main {
    public static class myThread extends Thread{
        @Override
        public void run() {
            
        }
    }
    public static class MyRunnable implements Runnable{
         @Override
         public void run() {

         }
}
    public static void main(String[] args) {
        myThread t1=new myThread();
        Thread t2=new Thread(new MyRunnable());
        Thread t3=new Thread("这是我的名字");
        Thread t4=new Thread(new MyRunnable(),"这是MyRunnable()创建出来的线程");

        t1.start();t2.start();t3.start();t4.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值