java多线程

一、实现多线程的三种方式:

        继承Thread类、实现Runnable接口(重点)、实现Callable接口

1、继承Thread

public class TestThread extends Thread{

    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("学习中。。。"+i);
        }
    }

    public static void main(String[] args) {
        //main线程
        //创建一个线程对象
        TestThread testThread = new TestThread();
        //调用start方法开启线程
        testThread.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main线程。。。"+i);
        }
    }
}

2、实现Runnable接口

public class TestRunnable implements Runnable{
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("学习中。。。"+i);
        }
    }

    public static void main(String[] args) {
        //main线程
        //创建Runnable接口的实现类对象
        TestRunnable  testRunnable = new TestRunnable();
        //创建线程对象,开启线程
        new Thread(testRunnable).start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main线程。。。"+i);
        }    
    }
}

3、实现Callable接口

public class TestCallable  {
    public static void main(String[] args) throws Exception {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);

        for (int i = 0; i < 5; i++) {
            Future<Integer> result = pool.schedule(new Callable<Integer>(){

                @Override
                public Integer call() throws Exception {
                    int num = new Random().nextInt(100);//生成随机数
                    System.out.println(Thread.currentThread().getName() + " : " + num);
                    return num;
                }

            }, 1, TimeUnit.SECONDS);

            System.out.println(result.get());
        }

        pool.shutdown();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值