1.继承Thread类并重写Run方法
public class MyThread extends Thread{
public MyThread() {
}
//可以通过有参构造方法在创建多线程的时候为线程设置名字
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//通过Thread.currentThread().getName()可以获得当前执行线程的名字
System.out.println(Thread.currentThread().getName()+"->"+i);
}
}
}
public class Demo {
public static void main(String[] args) {
//通过有参构造创建多线程并设置线程名字
MyThread t1=new MyThread("Thread");
//通过无参构造创建多线程
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
2.实现Runnable接口并重写run方法
public class RunnableImpl implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"->"+i);
}
}
}
public class Demo {
public static void main(String[] args) {
RunnableImpl r=new RunnableImpl();
Thread t1=new Thread(r);
t1.start();
Thread t2=new Thread(r);
t2.start();
}
}
3.使用匿名内部类创建多线程
public class Demo {
public static void main(String[] args) {
//使用匿名内部类创建Thread子类对象并调用start方法
new Thread() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "->" + i);
}
}
}.start();
//使用匿名内部类创建Runnable接口的实现类对象
//并将其作为参数传入Thread对象,开启多线程
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "->" + i);
}
}
}).start();
}