实现多线程的三种方式及区别

class mythread1 extends Thread {

    int num=10;
    @Override
    public void run() {
        while(num>0) {
            System.out.println(Thread.currentThread()+"-"+num--);
        }
    }
}
new mythread1().start();
class mythread2 implements Runnable {

    private int num = 10;
    @Override
    public void run() {
        while(num>0) {
            System.out.println(Thread.currentThread().getName()+"-"+num--);
        }
    }
}

 mythread2 a = new mythread2();
 mythread2 b = new mythread2();

 new Thread(a).start();

 new Thread(b).start();

class mythread3 implements Callable<Integer>{
    int num=10;
    @Override
    public Integer call() throws Exception {        
        while(num>0) {
            System.out.println(Thread.currentThread().getName()+"-"+num--);
        }
        return num;
        
    }    
}

mythread3 my3=new mythread3();
FutureTask<Integer> ft = new FutureTask<>(my3);
new Thread(ft,"有返回的线程").start();
try {
System.out.println("子线程的返回值:"+ft.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(ft,"有返回的线程").start();

 

实现接口的可以实现共享变量

猜你喜欢

转载自www.cnblogs.com/smallJunJun/p/10540409.html