创建线程的两种方式:
1.继承Thread并重写方法,在run方法中定义线程要执行的任务
class MyThread extends Thread {
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("who are you ");
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
Thread t1=new MyThread();
t1.start();
}
}
2.实现Runable接口并重写run方法
class MyRunnable implements Runnable{
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("I'm a fool");
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Runnable r1 =new MyRunnable();
Thread t1 = new Thread(r1);
t1.start();
}
}
3.两种方式的匿名内部类
public class ThreadDemo3 {
public static void main(String[] args) {
//使用直接继承线程方式
Thread t1 = new Thread() {
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("who are you ");
}
}
};
t1.start();
//使用实现Runnable接口方式
Runnable r2= new Runnable() {
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("I'm a fool");
}
}
};
Thread t2=new Thread(r2);
t2.start();
}
}