Java创建线程有两种方式
1.通过Runnable接口实现(推荐的方式)
(1)新建一个类实现Runnable接口,需要重写run方法
1 class MyRunnable implements Runnable{ 2 3 @Override 4 public void run() { 5 6 } 7 8 }
(2)新建一个线程对象,在构造器中传入实现了Runnable接口的类
Thread thread = new Thread(new MyRunnable);
(3)调用Thread的start方法
thread.start();
2.通过继承Thread类来实现
(1)新建一个类继承Thread类,需要重写run方法
1 class MyThread extends Thread{ 2 @Override 3 public void run() { 4 super.run(); 5 6 } 7 }
(2)调用Thread类的start方法。
MyThread thread = new MyThread(); thread.start();
3.示例
package thread; public class MultiThread { public static void main(String[] args){ //1.创建线程的第一种方法,利用接口创建实现了该接口的类 Runnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); //2.创建线程的第二种方法,利用Thread开启线程 但是不推荐 MyThread thread2 = new MyThread(); thread2.start(); } } class MyRunnable implements Runnable{ @Override public void run() { for(int i = 0; i< 10; i++){ try { System.out.println("利用runnable开启线程:" + i); Thread.sleep(1000); } catch (InterruptedException e) { } } } } class MyThread extends Thread{ @Override public void run() { super.run(); for (int i = 0; i < 10; i++) { try { System.out.println("利用Thread开启线程:"+i); Thread.sleep(1000); } catch (InterruptedException e) { } } } }
运行结果如下:
时间: 2024-10-18 16:53:46