线程join思考与创建线程的三种方式

[code=java]
public class MyJoin {
    public static void main(String[] args) throws InterruptedException {
        Th2 th2=new Th2();
        th2.setName("B");
        th2.start();
        th2.join();
        //th2对象先获得锁对象,
        //th2中的th1获取CPU资源,锁对象

        System.out.println("Main");
    }
}

class Th1 extends Thread{
    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(this.getName());
        super.run();
    }
}
class Th2 extends Thread{
    @Override
    public void run() {
        Th1 th1=new Th1();
        th1.setName("A");
        th1.start();
        System.out.println(this.getName());
        try {
            th1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(this.getName());
        super.run();
    }
}

B
A
B
Main
[/code]
三种方式是

extend Thread;

implement Runable接口

implement Callable接口 

    使用Future.run执行,或者线程池去执行

public static void main(String [] arg) throws InterruptedException, ExecutionException{
        // 这种方式  穿件的线程需要使用 FutureTask 类进行包装,才能使用 Thread.start() 启动
        // 例如
        Callable<String> t3 = new MyCall();
//        t3.wait();
          FutureTask<String> task = new FutureTask<String>(t3);
        new Thread(task).start();
        // 然后通过 task.get() 函数能够获取线程执行的结果(返回值)
        // 如果线程没有执行完,get() 函数会一直阻塞等到线程执行结束
        String val = task.get(); 
        // 另外可以通过 task.isDone() 函数校验是否执行完 - 该函数不阻塞
        if(task.isDone()){
            String val1 = task.get();
            System.out.println(val1);
        }else{
            System.out.println("未执行完");
        }
        // 配合线程池使用 返回 Future 可以通过 Future 获取执行结果
        ExecutorService executor = Executors.newFixedThreadPool(2);//任务较重的服务器,
        Future<String> val2 = executor.submit(t3); 
        System.out.println(val2.get());     
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值