线程基础介绍一

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函数的运行


使用Runnable接口:
		Dog dog=new Dog();
		//创建一个线程对象
		Thread t= new Thread(dog);
		t.start();

我们再进一步分析,在java中类的继承是单继承的,因而我们经常会碰到某些类已经继承了某一个父类,那么,显然不能再用继承Thread方法来实现多线程了,因此,再实战中我们往往更倾向于使用Runnable接口,因为接口是可以多个使用的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值