您的位置:首页 > 教育 > 培训 > Java多线程的代码实现

Java多线程的代码实现

2025/5/23 21:59:12 来源:https://blog.csdn.net/2301_80427749/article/details/142299373  浏览:    关键词:Java多线程的代码实现

①:继承Thread,重写run方法

class MyThread extends Thread {

                public void run() {

                 //创建出的线程需要执行的逻辑

                 System.out.println("hello thread");

                }

}

public class Demo1 {

                public static void main(String[] args) {

                         MyThread t = new MyThread();

                         //真正在系统内核创建线程

                         t.start();

                }

}

②:实现Runnable接口,重写run方法

class MyRunnable implements Runnable {

                         public void run() {

                         //创建出的线程需要执行的逻辑

                         System.out.println("hello thread");

                         }

}

public class Demo2 {

           public static void main(String[] args) {

           MyRunnable runnable = new MyRunnable();

           Thread t = new Thread(runnable);

           //真正在系统内核创建线程

           t.start();

           }

}

③:用匿名内部类实现继承Thread,重写run方法,本质上和①一样

public class Demo3 {

         public static void main(String[] args) {

                 Thread t = new Thread() {

                         //创建出的线程需要执行的逻辑

                         public void run() {

                               System.out.println("hello thread");

                         }

                 };

                 //真正在系统内核创建线程

                 t.start();

         }

}

④:用匿名内部类实现Runnable,重写run方法,本质上和②一样

public class Demo4 {

      public static void main(String[] args) {

                Thread t = new Thread(new Runnable() {

                               //创建出的线程需要执行的逻辑

                               public void run() {

                                       System.out.println("hello thread");

                               });

                t.start();

      }

}

⑤:用lambda表达式

public class Demo5 {

          public static void mian(String[] args) {

                   Thread t = new Thread( () -> {

                            System.out.println("hello thread");

                    });

                    t.start();

          }

}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com