一,关于线程的基本概念
一个独立程序的每一次运行成为一个进程。
每个进程又可以包含多个同时执行的子任务,对应多个线程。
将一个进程分解为互不影响的多个线程,可以使多个线程并行执行,大大缩短了执行时间。
二,通过继承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读取等,我们可以重新开启一个线程,在新线程里面放入我们要执行的操作,以保证我们其他操作不受影响。