创建多线程
一、继承Thread类,重写run方法
Thread类在java.lang包
public class ThreadDemo {
public static void main(String[] args) {
//当前处于main方法的线程
System.out.println(Thread.currentThread().getName());
twoThread t2 = new twoThread();
//start()启动线程
t2.start();
}
}
class twoThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"继承Thread类,重写run方法");
}
}
二、通过Runnable接口实现run方法
Runnable接口在java.lang包下
public class ThreadDemo2 {
public static void main(String[] args){
//当前处于main方法的线程
System.out.println(Thread.currentThread().getName());
oneThread target = new oneThread();
//接口实现类的实例作为Thread的target作为参数传入Thread有参构造
Thread t1 = new Thread(target);
//可简化成
//Thread t1 = new Thread(new MyThread());
t1.start();
}
}
class oneThread implements Runnable {
@Override
public void run() {
// currentThread().getName()获取当前线程的名字
System.out.println(Thread.currentThread().getName() + "通过Runnable接口实现run方法");
}
}