1、继承Thread类:此类实现简单,但不可以资源共享
package com.sxt;
public class ThreadDmeo extends Thread{
//继承Thread类
@Override
public void run() {
for(int i=0;i<1000;i++) {
System.out.println(Thread.currentThread().getName()+i);
}
}
public static void main(String[] args) {
ThreadDmeo td = new ThreadDmeo();
ThreadDmeo tde = new ThreadDmeo();
td.start(); //通过start方法启动线程
tde.start();
for(int i=0;i<1000;i++) {
System.out.println("狗");
}
}
}
2、实现Runnable 接口。优点:避免单继承局限,只实现一个Runnable子类对象,可以资源共享
package com.sxt;
public class RunnableDmeo implements Runnable { //继承Runnable接口
@Override
public void run() {
for(int i=0;i<1000;i++)
System.out.println(Thread.currentThread().getName()+i);
}
public static void main(String[] args) throws Exception {
RunnableDmeo r = new RunnableDmeo(); //实例化对象
Thread t1 = new Thread(r,"线程1:"); //把Runnable子类对象传入Thread构造方法
t1.start();
Thread t2 = new Thread(r,"线程2:");
t2.start();
Thread.sleep(1000); //睡眠时间毫秒值
Thread t3 = new Thread(r);
t3.setName("线程3:");
t3.start();
}
}