java 多线程--------(一)

创建线程的3种方式

1、继承Thread类,复写run方法,run方法中为线程需要执行的逻辑部分,而启动线程调用start方法。小示例见代码,通过Thread.currentThread().getName()可以获得当前线程名称

public class MyThread extends Thread {
   private int i;
   public void run(){
       for(;i<100;i++){
           System.out.println(Thread.currentThread().getName()+" "+i);
       }
   }
};

 public static void main(String[] args) {
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+""+i);
            if(i==20){
               new MyThread().start();
               new MyThread().start();
            }
        }
    }

2、由于java不支持多继承,当需要继承另一个类时,与第一种方式冲突。于是可以使用第二种方法,通过实现Runnable接口。复写run方法。代码下

public class MyThread2 implements Runnable{
     private int i;
    @Override
    public void run() {
        for(;i<100;i++){
           System.out.println(Thread.currentThread().getName()+" "+i);
       }
    }
}
    public static void main(String[] args) {
          for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+""+i);
            if(i==20){
                MyThread2 myThread2 = new MyThread2();
               new Thread(myThread2).start();
               new Thread(myThread2).start();
            }
     
    }

3使用callable和future,Callable()与Runable()不同的地方主要是,Callable方法有返回值。代码如下

public class CallableDemo implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int i = 5;
        for(;i<100;i++){
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
        return i;
    }
}


 public static void main(String[] args) {
        CallableDemo callableDemo = new CallableDemo();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(callableDemo);
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+""+i);
            if(i==20){
               new Thread(futureTask,"有返回的线程:").start();
               try {
                   System.out.println("子线程的返回值" + futureTask.get());
               }catch(Exception e){
                    e.printStackTrace();
               }
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/gloria-liu/p/10430840.html