目录
一、进程和线程
二、线程的创建
1.继承Thread类,重写run()方法
2.实现Runnable接口,重写run方法
3.匿名线程,匿名内部类
4.实现Callable接口,重写call方法
三 、叫号系统测试
四、start方法剖析
一、进程和线程
进程指的一段正在运行的程序。
一个程序运行中可以执行多个任务,任务称之为线程。
每个进程有自己独立的地址空间,多并发请求,为每一个请求创建一个进程 导致系统开销、用户请求效率低,因此出现了进程这个概念,Java中的JVM是一个进程。
区别:
- 进程是程序执行过程中资源分配和管理的基本单位,线程是cpu执行的额最小单位 。
- 进程拥有自己的独立的地址空间,每启动一个进程,系统就会分配地址空间 进程可以拥有多个线程,各个线程之间共享程序的内存空间 。
- 每个进程拥有自己独有的数据,线程共享数据 线程之间的通信相比于进程之间的通信更有效 更容易
- 线程相比于进程创建/销毁开销更小
- 进程是资源分配的最小单位,线程是cpu调度的最小单位
- 多进程程序更加健壮,多线程程序只要有一个线程挂掉,对其共享资源的 其他线程也会产生影响
- 如果追求速度,选择线程 如果频繁创建和销毁,选择线程 如果追求系统更加稳定,选择进程 线程是轻量级的进程
二、线程的创建
1.继承Thread类,重写run()方法
main函数中有一个线程A,创建一个类继承Thread,重写其中的run方法,称为线程B,通过Thread创建对象,利用start方法启动线程。
class MyThread extends Thread{
@Override
public void run() {
//子线程执行体
int i = 0;
while(true){
System.out.println("thread B........");
// System.out.println("thread B......."+(++i));
}
}
}
public class test1 {
public static void main(String[] args) {
int i = 0;
Thread thread = new MyThread();
thread.start();//start -> run
//main线程
while(true){
System.out.println("thread A........");
// System.out.println("thread A......."+(++i));
}
}
}
线程的执行顺序不是按代码中书写顺序,或者说是主函数中先执行主线程再执行子线程,而是两个线程之间相互抢占CPU,哪个抢到了就执行哪个,是随机性的。
也可以加入线程执行次数限制或计数器方便理解。
class MyThread extends Thread{
@Override
public void run() {
//子线程执行体
int i = 0;
while((i++) < 20){
System.out.println("thread B........");
// System.out.println("thread B......."+(++i));
}
}
}
public class test1 {
public static void main(String[] args) {
int i = 0;
//System.out.println("begin:");
Thread thread = new MyThread();
System.out.println("begin:");
thread.start();//start -> run
//main线程
while((i++) < 20){
System.out.println("thread A........");
// System.out.println("thread A......."+(++i));
}
}
}
2.实现Runnable接口,重写run方法
通过实现Runnable接口,对run方法重写,不同点在与Thread对象的创建,应该把Runnable当成参数传入。
class MyRunnable implements Runnable{
@Override
public void run() {
while(true){
System.out.println("thread B.......");
}
}
}
public class test1 {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
while (true) {
System.out.println("thread A......");
}
}
}
3.匿名线程,匿名内部类
public static void main(String[] args) {
new Thread(){
@Override
public void run() {
while(true){
System.out.println("thread B.......");
}
}
}.start();
}
4.实现Callable接口,重写call方法
Callable接口存在Executor框架中类,相比于Runnable更加强大
- a.Callable可以在任务执行结束之后提供一个返回值
- b.call方法可以抛出异常
- c.运行Callable任务可以拿到一个Future对象,Future提供get方法 拿到返回值(异步)
Executor是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果。
通过Callable和FutureTask创建线程顺序:
a.创建Callable接口的实现类,重写call方法
class MyCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 10000; i++) {
sum += i;
}
return sum;
}
}
b.创建Callable实现类的实例,使用FutureTask包装该实例
c.将FutureTask实例作为参数创建线程对象
d.启动该线程
e.调用FutureTask的get方法获取子线程的执行结果
public static void main(String[] args) {
Callable<Integer> callable = new MyCallable();
FutureTask<Integer> task = new FutureTask<>(callable);
Thread thread = new Thread(task);
thread.start();
//接收线程执行后的结果
try {
Integer integer = task.get();
System.out.println("result:"+integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
Callable 和 Future接口的区别
- Callable规定的方法是call(),而Runnable规定的方法是run().
- Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
- call()方法可抛出异常,而run()方法是不能抛出异常的。
- 运行Callable任务可拿到一个Future对象, Future表示异步计算的结果。
- 它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。
- 通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。
- Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。
下面两张关系图有助于理解,来源于https://blog.csdn.net/sinat_39634657/article/details/81456810,该博主总结的很全面。
三 、叫号系统测试
以银行的叫号系统为例,银行中有多个柜台,号码从1开始,多个柜台随机叫号,号码保证不重复,且按照顺序叫号。
实现如下:
class TicketSystem extends Thread{
private String name;
private int index = 1;//号码,从1开始
private static final int max = 50;//号码最大值
public TicketSystem(String name) {
this.name = name;
}
@Override
public void run() {
while(index <= max){
System.out.println("办理柜台:"+name+",当前号码:"+index++);
}
}
}
public class test2 {
public static void main(String[] args) {
TicketSystem ticketSystem1 = new TicketSystem("1号");
ticketSystem1.start();
TicketSystem ticketSystem2 = new TicketSystem("2号");
ticketSystem2.start();
TicketSystem ticketSystem3 = new TicketSystem("3号");
ticketSystem3.start();
TicketSystem ticketSystem4 = new TicketSystem("4号");
ticketSystem4.start();
TicketSystem ticketSystem5 = new TicketSystem("5号");
ticketSystem5.start();
}
}
经测试结果出现重复不按照顺序叫号的情况,原因是index变量是每一个柜台的私有变量,应该将它改成共享变量,就可以保证是对同一变量进行操作了。当号码最大值较大如1000时,线程就会出现安全问题,导致号码重复乱序甚至大于最大值的现象。
利用Runnable接口实现叫号:
class TicketSystemTask implements Runnable{
private String name;
private int index = 1;//号码,从1开始
private static final int max = 50;//号码最大值
@Override
public void run() {
while(index <= max){
System.out.println("办理柜台:"+Thread.currentThread().getName()+",当前号码:"+index++);
}
}
}
public class test2 {
public static void main(String[] args) {
TicketSystemTask task = new TicketSystemTask();
Thread thread1 = new Thread(task, "1号柜台");
Thread thread2 = new Thread(task, "2号柜台");
Thread thread3 = new Thread(task, "3号柜台");
Thread thread4 = new Thread(task, "4号柜台");
Thread thread5 = new Thread(task, "5号柜台");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
四、start方法剖析
start方法首先将线程加入一个线程组中,这时该线程进入Runnable就绪状态,start0获取cpu资源执行程序自定义的run方法
run方法就是一个普通的方法,不会启动一个新的线程 注意:线程在调用start方法的时候会有一个threadStatus,如果不等于0说明已经启动,不能够重复启动,重复启动抛异常IllegalThreadStateException。
public synchronized void start() {
if(threadStatus!=0)//判断当前线程状态是否为0
throw new IllegalThreadStateException();
group.add(this); //当前线程加入一个线程
boolean started=false;
try{
start0(); //start0是一个native本地方法 调用run执行该线程
started=true;
}finally{
try{
if(!started){
group.threadStartFailed(this);
}
}catch(Throwable ignore){
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)