标签:static 使用 因此 接口 extend 多线程 extends public art
创建线程有三种方式:
1.继承Thread类
public class MyThread00 extends Thread
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println(Thread.currentThread().getName() + "在运行!");
}
}
}
public static void main(String[] args)
{
MyThread00 mt0 = new MyThread00();
mt0.start();
for (int i = 0; i < 5; i++)
{
System.out.println(Thread.currentThread().getName() + "在运行!");
}
}
2.实现Runnable接口
public class MyThread01 implements Runnable
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println(Thread.currentThread().getName() + "在运行!");
}
}
}
public static void main(String[] args)
{
MyThread01 mt0 = new MyThread01();
Thread t = new Thread(mt0);
t.start();
for (int i = 0; i < 5; i++)
{
System.out.println(Thread.currentThread().getName() + "在运行!");
}
}
两种多线程实现方式的对比
Thread类也是实现了Runnable接口。两种方式比较,当然实现接口好一些。因为第一继承只能单继承,实现可以多实现。第二,实现的方式利于松耦合。因此多线程的实现几乎都是使用Runnable接口的方式。
标签:static 使用 因此 接口 extend 多线程 extends public art
原文地址:https://www.cnblogs.com/tp123/p/11985650.html