线程的多种创建方式

方法一:继承Thread类,作为线程对象存在(继承Thread对象)

public class CreateThreadDemo1 extends Thread{
    /**
     * 构造方法:继承父类方法的Thread(String name)方法
     * @param name
     */
    public CreateThreadDemo1(String name){
        super(name);
    }

    @Override
    public void run(){
        while(!interrupted()){
            System.out.println(getName() + "线程执行了....");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        CreateThreadDemo1 c1 = new CreateThreadDemo1("first");
        CreateThreadDemo1 c2 = new CreateThreadDemo1("second");

        c1.start();
        c2.start();

        c1.interrupt(); //中断第一个线程
    }
}

interrupted方法,是来判断该线程是否被中断。(终止线程不允许用stop方法,该方法不会释放占用的资源。所以我们在设计程序的时候,要按照中断线程的思维去设计,就像上面的的代码一样)。

让线程等待的方法:

Thread.sleep(2000; //线程休息2秒

Object.wait(); //让线程进入等待,直到调用Object的notify或者notifyAll时,线程停止休眠;

方法二:实现runnable接口,作为线程任务存在

public class CreateThreadDemo2 implements Runnable {
    @Override
    public void run() {
        while (true){
            System.out.println("线程执行了....");
        }
    }

    public static void main(String[] args){
        //将线程任务传给线程对象
        Thread t = new Thread(new CreateThreadDemo2());
        //启动线程
        t.start();
    }
}

Runnable只是来修饰线程所执行的任务,它不是一个线程对象。想要启动Runnable对象,必须将它放到一个线程对象里。

方法三:匿名内部类创建线程对象

public class CreateThreadDemo3 extends Thread {

    public static void main(String[] args){
        //创建无参线程对象
        new Thread(){
            @Override
            public void run(){
                System.out.println("线程执行了.....");
            }
        }.start();

        //创建带线程任务的线程对象
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程执行了.....");
            }
        }).start();

        //创建带线程任务并重写run方法的线程对象
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Runnable run线程执行了.....");
            }
        }){
            @Override
            public void run() {
                System.out.println("Override run线程执行了.....");
            }
        }.start();
    }
}

Thread实现了Runnable接口,而Runnable接口里面有一个run方法,我们最终调用的重写的方法应该是Tread类的run方法,而不是Runnable接口的run方法。

方法四:创建带返回值的线程

public class CreateThreadDemo4 implements Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CreateThreadDemo4 demo4 = new CreateThreadDemo4();
        //FutureTask是最终实现的是runnable接口
        FutureTask<Integer> task = new FutureTask<Integer>(demo4);
        Thread t = new Thread(task);
        t.start();
        System.out.println("我可以在这里做点别的业务逻辑..因为FutureTask是提前完成任务");
        //拿出线程执行的返回值
        Integer result = task.get();
        System.out.println("线程中运算的结果为:" + result);
    }

    //重写Callable接口的call方法
    @Override
    public Object call() throws Exception {
        int result = 1;
        System.out.println("业务逻辑计算中...");
        Thread.sleep(3000);
        return result;
    }
}

返回指定泛型的call方法。然后调用FutureTask对象的get方法得到call方法的返回值。

方法五:定时器Timer

public class CreateThreadDemo5 {
    public static void main(String[] args){
        Timer t = new Timer();

        t.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("定时器线程执行了...." );
            }
        },0,1000);  //延迟0,周期1s
    }
}

方法六:线程池创建线程

public class CreateThreadDemo6 {
    public static void main(String[] args){
        //创建一个具有10个线程的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        long threadpoolUseTime = System.currentTimeMillis();
        for(int i = 0 ; i < 10; i++){
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"线程执行了...");
                }
            });
        }
        long threadpoolUseTime1 = System.currentTimeMillis();
        System.out.println("多线程用时" + (threadpoolUseTime1 - threadpoolUseTime));
        //销毁线程池
        threadPool.shutdown();
        threadpoolUseTime = System.currentTimeMillis();
    }
}

方法七:利用Java8新特性Stream实现并发

public class CreateThreadDemo7 {
    public static void main(String[] args){
        List<Integer> values = Arrays.asList(10,20,30,40);
        //parallel平行的,并行的
        int result = values.parallelStream().mapToInt(p->p*2).sum();
        System.out.println(result);
        values.parallelStream().forEach(p->System.out.println(p));
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值