Java——Thread/Runnable实现多线程



 一,关于线程的基本概念



                         一个独立程序的每一次运行成为一个进程。

              每个进程又可以包含多个同时执行的子任务,对应多个线程。

              将一个进程分解为互不影响的多个线程,可以使多个线程并行执行,大大缩短了执行时间。


二,通过继承Thread类实现新线程


 

public class FactorialThreadTester {

	/**
	 * 主线程
	 */
	public static void main(String[] args) {
		System.out.println("main thread starts");
		FactorialThread thread=new FactorialThread(10);
		thread.start();  //开启新线程
		System.out.println("main thread ends");

	}
}

/*
 * 新类继承Thread,实现run方法
 * */
class FactorialThread extends Thread{

	private int num;
	public FactorialThread(int num){
		this.num=num;
	}
	@Override
	public void run() {
		int i=num;
		int result=-1;
		System.out.println("new thread started");
		while(i>0){
			result=result*i;
			i=i-1;
		}
		System.out.println("the factorial of "+num+"  is :"+result);
		System.out.println("new thread ends");
		}
		
	}



结果:





三,通过实现Runnable接口实现多线程


public class ImplementRunnableDemo {
	public static void main(String[] args) {
		System.out.println("main thread starts");
		FacorialThread f=new FacorialThread(10);
		new Thread(f).start();//开启新线程
		System.out.println("new thread started,main thread ends");
	}
}

/*
 * 
 * 通过实现Runnable接口实现多线程,实现接口中run方法
 * */
 class FacorialThread implements Runnable{

	 private int num;
		public FacorialThread(int num){
			this.num=num;
		}
		@Override
		public void run() {
			int i=num;
			int result=-1;
			System.out.println("new thread started");
			while(i>0){
				result=result*i;
				i=i-1;
			}
			System.out.println("the factorial of "+num+"  is :"+result);
			System.out.println("new thread ends");
			}
			
	
	
}




       这种方法跟继承Thread类其实没多大区别,只不过因为Java是单继承语言,可能实现多线程的类已经继承了别的父类,在是时候,可以通过实现接口的方式来实现多线程。



     可以从执行结果看出,当开启新线程之后,主线程继续执行,也就是说程序的执行并没有阻塞在新线程的start方法中。

 

         因此,在执行耗时操作,比如网络操作,IO读取等,我们可以重新开启一个线程,在新线程里面放入我们要执行的操作,以保证我们其他操作不受影响。







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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值