软件编程
位置:首页>> 软件编程>> java编程>> Java创建线程的五种写法总结

Java创建线程的五种写法总结

作者:学好c语言的小王同学  发布时间:2023-01-10 04:39:34 

标签:Java,创建,线程

通过继承Thread类并实现run方法创建一个线程

// 定义一个Thread类,相当于一个线程的模板
class MyThread01 extends Thread {
   // 重写run方法// run方法描述的是线程要执行的具体任务@Overridepublic void run() {
       System.out.println("hello, thread.");
   }
}

// 继承Thread类并重写run方法创建一个线程

public class Thread_demo01 {
   public static void main(String[] args) {
       // 实例化一个线程对象
       MyThread01 t = new MyThread01();
       // 真正的去申请系统线程,参与CPU调度
       t.start();
   }
}

通过实现Runnable接口,并实现run方法的方法创建一个线程

// 创建一个Runnable的实现类,并实现run方法
// Runnable主要描述的是线程的任务
class MyRunnable01 implements Runnable {
   @Overridepublic void run() {
       System.out.println("hello, thread.");
   }
}
//通过继承Runnable接口并实现run方法

public class Thread_demo02 {
   public static void main(String[] args) {
       // 实例化Runnable对象
       MyRunnable01 runnable01 = new MyRunnable01();
       // 实例化线程对象并绑定任务
       Thread t = new Thread(runnable01);
       // 真正的去申请系统线程参与CPU调度
       t.start();
   }
}

通过Thread匿名内部类创建一个线程

//使用匿名内部类,来创建Thread 子类
public class demo2 {
   public static void main(String[] args) {
       Thread t=new Thread(){ //创建一个Thread子类 同时实例化出一个对象
           @Override
           public void run() {
               while (true){
                   System.out.println("hello,thread");
                   try {
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }
       };
       t.start();
   }
}

通过Runnable匿名内部类创建一个线程

public class demo3 { //使用匿名内部类 实现Runnable接口的方法
   public static void main(String[] args) {
       Thread t=new Thread(new Runnable() {

@Override
           public void run() {
               while (true){
                   System.out.println("hello Thread");
                   try {
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }

}
       });
       t.start();
}
}

通过Lambda表达式的方式创建一个线程

public class demo4 { //使用 lambda 表达式
   public static void main(String[] args) {
       Thread t=new Thread(()->{
           while (true){
               System.out.println("hello,Thread");
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }

});
       t.start();
   }
}

来源:https://blog.csdn.net/weixin_59796310/article/details/126409849

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com