屏东县网站建设_网站建设公司_服务器维护_seo优化
2025/12/19 7:00:06 网站建设 项目流程

目录

1.继承Thread类,并重写run()方法

2.实现Runnable接口,并重写run()方法

3.使用匿名内部类,继承Thread类,重写run方法

4.使用匿名内部类,实现Runnable接口,重写run()方法

5.使用lambda表达式


1.继承Thread类,并重写run()方法

//继承Thread类,并重写run方法 class MyThread extends Thread{ public void run(){ while(true){ System.out.println("hello thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } public class demo1 { public static void main(String[] args) throws InterruptedException { Thread t=new MyThread(); t.start(); //main线程执行的任务 while(true){ System.out.println("hello main"); Thread.sleep(1000); } } }

2.实现Runnable接口,并重写run()方法

//实现Runnable接口,并重写run()方法 class MyRunnable implements Runnable{ @Override public void run() { while(true){ System.out.println("hello thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } public class demo2 { public static void main(String[] args) { Runnable runnable=new MyRunnable(); Thread t=new Thread(runnable); t.start(); } }

3.使用匿名内部类,继承Thread类,重写run方法

//使用匿名内部类,继承Thread类,重写run方法 public class demo3 { public static void main(String[] args) { Thread t=new Thread(){ public void run(){ while(true){ System.out.println("hello thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }; t.start(); } }

4.使用匿名内部类,实现Runnable接口,重写run()方法

//使用匿名内部类,实现Runnable接口,重写run()方法 public class demo4 { public static void main(String[] args) { Runnable runnable=new Runnable() { @Override public void run() { while(true){ System.out.println("hello thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }; Thread t=new Thread(runnable); t.start(); } }

5.使用lambda表达式

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

使用lambda表示式,本质上是使用“匿名函数”,其最主要的用途是用作回调函数

在java中,方法必须要依托于类来存在,以上的函数式接口()->{},在编译器背后实际上做的工作是,创建一个匿名函数式接口的子类,并且创建出对应的实例,并重写了里面的方法。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询