1.继承Thread,重写run
class thread extends Thread {
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("run方法线程体" + i);
}
}
}
public class thread_run{
public static void main(String[] args) {
Thread t = new thread();
t.start();
}
}
2.实现Runable,重写run,把Runnable实例传入到Thread中
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("hello thread");
try{
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public class Thread_implements_runnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
3.使用匿名内部类继承Thread
public class Demo3 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
System.out.println("hello Thread");
}
};
t.start();
}
}
创建了一个Thread的子类,同时也创建了这个子类的实例,重写了run方法
4.匿名内部类实现Runnable
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello Thread");
}
});
5.使用lambda表达式
public class Demo5 {
public static void main(String[] args) {
Thread t = new Thread(()->{
System.out.println("hello Thread");
});
t.start();
}
}