多线程的三种实现方式

1、继承Thread类,重写run方法


public class MyThread extends Thread{
public void run(){
for(int i = 0;i<100;i++){
System.out.println(“”)
}
}
}

public class ThreadDemo(){
public static void main(String[] args){
MyThread mt1 = new MyThread();
MyThread mt2 - new MyThread();
mt1.setName(“线程1”);
mt2.setName(“线程2”);
mt1.start();
mt2.start();
}

}

2、实现Runnable接口,重写run方法
步骤:
1、创建MyRunnable类实现runnable接口
2、重写run方法
3、创建MyRunnable类的对象
4、创建Thread类的对象,并把MyRunnable类对象作为参数传递


public MyRunnable implements Runnable{
public void run(){
for(int i = 0;i<100;i++){
System.out.println(i);
}
}
}

public class MyRunnableDemo{
public static void main(String[] args){
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my,”线程1”);
Thread t2 = new Thread(my,”线程2”);
t1.start();
t2.start();
}
}

3、实现callable接口,重写call方法,可提供返回值
依赖于线程池使用

public class MyCallable implements Callable<Integer>{
    private int number;
    public MyCallable(int number){
        this.number = number;
    }
    public Integer call() throws Exception{
        int sum = 0;
        for(int i=1;i<number;i++){
            sum += i;
        }
        return sum;
    }
}

//测试类
public class CallableDemo{
    public static void main(String[] args) throws Exception{
        Executorservice pool = Executors.newFixedThreadPool(2);
        Future<Integer> f1 = pool.submit(new MyCallable(100));
        Future<Integer> f1 =pool.submit(new Mycallable(50));
        Integer i1 = f1.get();
        Integer i2 = f2.get();
        System.out.println("1-100的和是:" + i1);
        System.out.println("1-50的和是:" + i2);
        pool.shutdown;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值