第一种 继承Thread类
package org.fan.threaddemo; public class MyThread extends Thread{ private String name; public MyThread(String name){ this.name=name; } public void run(){//覆写run()方法 for(int i=0;i<30;i++){ System.out.println("Thread运行:"+this.name+",i="+i); } } } //================= package org.fan.threaddemo; public class ThreadDemo01 { public static void main(String[] args) { MyThread mt1=new MyThread("线程A"); MyThread mt2=new MyThread("线程B"); mt1.run(); mt2.run(); } } //================ package org.fan.threaddemo; public class ThreadDemo02 { public static void main(String[] args) { MyThread mt1=new MyThread("线程A"); MyThread mt2=new MyThread("线程B"); mt1.start(); mt2.start(); } }
第二种 实现Runnable接口
package org.fan.runnabledemo; public class MyThread implements Runnable{ private String name; public MyThread(String name){ this.name=name; } public void run(){//覆写run()方法 for(int i=0;i<30;i++){ System.out.println("Thread运行:"+this.name+",i="+i); } } } //=================== package org.fan.runnabledemo; public class RunnableDemo01 { public static void main(String[] args) { MyThread mt1=new MyThread("线程A"); MyThread mt2=new MyThread("线程B"); new Thread(mt1).start(); new Thread(mt2).start(); } }
JavaLearning:多线程的两种实现方式
时间: 2024-10-10 23:12:13