当前位置: 代码迷 >> 综合 >> Java实现多线程的2种方法( Thread ,Runnable )
  详细解决方案

Java实现多线程的2种方法( Thread ,Runnable )

热度:92   发布时间:2023-10-09 16:53:35.0
1,继承Thread类

a:新建一个类继承Thread类

b:重写run()函数

c:创建该类对象

d:启动线程start()

2.实现Runnable接口

a:新建一个类实现Runnable接口

b:重写run()函数

c:创建该类的对象myRunnable

d:创建Thread对象 Thread th = new Thread(myRunnable);

e:启动线程th.start();


继承Thread类

public class Thread1 extends Thread{public static void main(String[]args){Thread1 th1 = new Thread1();th1.start();}@Overridepublic void run() {System.out.println("继承Thread类实现多线程");}}


实现Runnable接口

public class Thread2 implements Runnable{public static void main(String[]args){Thread2 myThread = new Thread2();Thread th2 = new Thread(myThread);th2.start();}@Overridepublic void run() {System.out.println("实现Runnable接口实现多线程");}}



  相关解决方案