文章目录
一、线程是什么?
线程(英语:thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。在Unix System V及SunOS中也被称为轻量进程(lightweight processes),但轻量进程更多指内核线程(kernel thread),而把用户线程(user thread)称为线程。
1.创建方式
1.1方式一:继承java.lang.Thread类(线程子类)
public class Test {
public static void main(String[] args) {
SubThread thread = new SubThread();
thread.start();
}
}
class SubThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("我是子线程:" + i);
}
}
}
结果如图:
1.2方式二:实现java.lang.Runnable接口(线程执行类)
public class Test {
public static void main(String[] args) {
SubThread st = new SubThread();
Thread thread = new Thread(st);
thread.start();
}
}
class SubThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("我是子线程:" + i);
}
}
}
结果如图:
1.3方式三:实现java.util.concurrent.Callabel接口,允许子线程返回结果,抛出异常
public class Test {
public static void main(String[] args) throws Exception {
//计算1-100累加和的值
SubThread st = new SubThread(1, 100);
FutureTask<Integer> task = new FutureTask<Integer>(st);
Thread thread = new Thread(task);
thread.start();
int ret = task.get();
System.out.println(ret);
}
}
class SubThread implements Callable<Integer> {
private int begin, end;
public SubThread(int begin, int end) {
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
int ret = 0;
for (int i = begin; i <= end; i++) {
ret += i;
}
return ret;
}
}
结果如图:
1.4方式四:线程池
线程池,按照配置参数(核心线程数、最大线程数等)创建并管理若干线程对象。程序中如果需要使用线程,将一个执行任务传给线程池,线程池就会使用一个空闲状态的线程来执行这个任务。执行结束以后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。使用线程池可以很好地提高性能。
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(10);
while (true) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("当前运行的线程名称为:" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
结果如图: