第一种:通过继承Thread类创建线程
步骤:
1.定义Thread类的子类,并重写该类的run方法,该方法的方法体就是线程需要执行的任务,因此run()方法也被称为线程执行体
2.创建Thread子类的实例,也就是创建了线程对象
3.启动线程,即调用线程的start()方法
class MyThread3 extends Thread{
public void run() {
while (true) {
System.out.println("hello thread");
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
public class Demo2 {
public static void main(String[] args) {
Thread thread=new MyThread3();
thread.start();
}
}
第二种:通过实现Runnable接口创建线程
步骤:
1.定义Runnable接口的实现类,重写run()方法,和第一种方式一样,这里的run()方法也是线程的执行体
2.创建Runnable实现类的实例,并用这个实例作为Thread的target来创建Thread对象,这个Thread类才是真正的线程对象
3.启动线程,即调用线程的start()方法
/**
* 通过实现Runnable接口创建线程
* Runnable是一个任务
* 1.创建Runnable的子类
* 2.创建该子类的实例,并交给一个线程的实例
* 3.启动该线程
*/
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("my runnable");
}
}
public class Demo3 {
public static void main(String[] args) {
MyRunnable runnable=new MyRunnable();
Thread thread=new Thread(runnable);
thread.start();
}
}
第三种:匿名内部类得方式创建Thread子类
public class Demo4 {
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
System.out.println(1111);
}
};
thread.start();
}
}
第四种:匿名内部类的方式创建Runnable的子类
public class Demo5 {
public static void main(String[] args) {
Runnable runnable=new Runnable() {
@Override
public void run() {
System.out.println(4444);
}
};
Thread thread=new Thread(runnable);
thread.start();
}
}
第五种:通过Lambda表达式的方式创建一个线程
public class Demo3 {
public static void main(String[] args) {
Thread t = new Thread(()->{
while(true){
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
文章详细介绍了在Java中创建线程的五种方法:1)继承Thread类;2)实现Runnable接口;3)使用匿名内部类创建Thread子类;4)匿名内部类创建Runnable子类;5)利用Lambda表达式创建线程。每种方式都包含了创建线程的基本步骤,如重写run方法和调用start方法来启动线程。
5459

被折叠的 条评论
为什么被折叠?



