Java-多线程

多线程的优势

1.线程间可以共享内存,文件句柄,和其他每个进程应有的状态。创建线程开销小。

线程的创建和启动过程。

①继承Thread类创建线程类

②实现runnable接口

③使用Callable和future创建线程

这个callable比Runnable接口的优势是,call()方法有返回值。且可以声明抛出异常。使用案例如下:

public class ThirdThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int i=0;
        for (;i<100;i++){
            System.out.println(Thread.currentThread().getName()+i);
        }
        return i;
    }

    public static  void main(String[]args){
       ThirdThread thirdThread = new ThirdThread();
        FutureTask task = new FutureTask(thirdThread) ;
     for (int i=0;i<100;i++){
         System.out.println(Thread.currentThread().getName()+i);
         if (i==20){
             new Thread(task,"有返回值的线程").start();
         }
     }
        try {
            System.out.println("子线程的返回值:"+task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ExecutionException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}


继承Thread与实现Runnable callable的接口的优势与不足:

1.继承Thread,则可以直接使用this访问当前线程。但限定的比较死,不能再继承其它类了。

2.实现Runnable callable接口,可以共享同一个目标对象,访问当前线程,必须使用Thread.currentThread()方法。


线程的生命周期:

new(新建)  Runnable(就绪)  running(运行) Blocked(阻塞) Dead(死亡)

状态转换图:





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值