java中实现我们一般用继承Thread类或使用Runnable接口来实现线程
首先我们来看两个简单的程序,感受一下这两者的写法区别
/*
* 演示如何通过继承Thread来开发线程
*/
package demo02;
public class Demo03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建一个Cat对象
Cat cat = new Cat();
//启动线程
cat.start(); //这句话会导致run函数的运行
}
}
class Cat extends Thread{
int time=0;
//重写run函数
public void run(){
while(true){
//休眠一秒
//1000表示1000毫秒,sleep就会让线程进入阻塞状态(blocked)
//并释放资源
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time++;
System.out.println("hello world");
if (time==10)
{
//退出线程
break;
}
}
}
}
/*
* 两个线程同时运行案例
*/
package demo03;
public class Demo03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Pig pig= new Pig(10);
Bird bird = new Bird(10);
Thread t1=new Thread(pig);
Thread t2=new Thread(bird);
t1.start();
t2.start();
}
}
//打印helloworld
class Pig implements Runnable{
int n=0;
int time=0;
public Pig(int n){
this.n=n;
}
public void run(){
while(true){
try{
Thread.sleep(1000);
}catch(Exception e){
}
time++;
System.out.println("我是一个线程,在输出第"+time+"个 hello world");
if(time==n)
{
break;
}
}
}
}
//鸟算数学题
class Bird implements Runnable{
int n=0;
int res=0;
int time=0;
public Bird(int n)
{
this.n=n;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try{
Thread.sleep(1000);
}catch(Exception e){
}
res+=(++time);
System.out.println("当前结果"+res);
if (time==n)
{
System.out.println("最后结果"+res);
break;
}
}
}
}
由以上两个程序我们发现继承Thread类和使用Runnabl接口十分相似,唯一不同的是使用Runnable接口我们会在主函数中先实例化子类,再用Thread类实例
可以感受一下:继承Thread:
//创建一个Cat对象
Cat cat = new Cat();
//启动线程
cat.start(); //这句话会导致run函数的运行
Dog dog=new Dog();
//创建一个线程对象
Thread t= new Thread(dog);
t.start();
我们再进一步分析,在java中类的继承是单继承的,因而我们经常会碰到某些类已经继承了某一个父类,那么,显然不能再用继承Thread方法来实现多线程了,因此,再实战中我们往往更倾向于使用Runnable接口,因为接口是可以多个使用的