1.继承Thread类
class TestThread extends Thread
{
@Override
public void run()
{
for(int i=1;i<=10;i++)
System.out.println("线程"+Thread.currentThread().getName()+"运行第"+i+"次");
}
}
public class JustATest{
public static void main(String[] args) {
new TestThread().start();
}
}
我们在TextThread类中重写了Thread类中的run方法,然后在main函数里通过start开始线程。
2.实现Runable接口
class TestThread implements Runnable
{
private int i=10;
public void run()
{
for(;i>0;i--)
System.out.println("线程"+Thread.currentThread().getName()+"运行第"+i+"次");
}
}
public class JustATest{
public static void main(String[] args) {
TestThread a=new TestThread();
new Thread(a,"1").start();
new Thread(a,"2").start();
new Thread(a,"3").start();
}
}
在实现Runable接口后,我们将一个TestThread的实例传入一个Thread对象中,并通过start开启。
因为Thread保留了TestThread实例的引用,所以当任意一个线程调用run方法时都会对实例a的属性i进行操作,理论上三个线程应该一共执行十次,但因为多个线程共同执行,使得运行结果如下:
线程1运行第10次
线程3运行第10次
线程2运行第10次
线程3运行第8次
线程1运行第9次
线程3运行第6次
线程2运行第7次
线程3运行第4次
线程1运行第5次
线程3运行第2次
线程2运行第3次
线程1运行第1次
进程已结束,退出代码为 0
这时我们可以使用同步代码块保证线程的安全。