多线程

1.新建多线程3中方式:

  1)继承Thread: 

public class ThreadExtends {
    public static void main(String[] args) {
        MyThread mt=new MyThread();
        mt.start();
        for (int i = 0; i <200 ; i++) {
            System.out.println("当前执行的线程:"+Thread.currentThread().getName()+"-"+i);  //获取当前线程名字
        }
    }
}
class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <200 ; i++) {
            try {
                Thread.sleep(1);           //sleep 是静态方法
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("当前执行的线程:"+Thread.currentThread().getName()+"-"+i);  //获取当前线程名字
        }
    }
}

  2)实现Runnable:

public class ThreadRunnbleDemo {
    public static void main(String[] args) {
        MyRunnable r=new MyRunnable();
        Thread t=new Thread(r);
        t.start();
        for (int i = 0; i <200 ; i++) {
          System.out.println("当前执行的线程:"+Thread.currentThread().getName()+""+i); 
        }
    }
}
class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i <200 ; i++) {
          System.out.println("当前执行的线程:"+Thread.currentThread().getName()+""+i);  
        }
    }

}

  3)线程池(也是实现Runnable) 

public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService  pool= Executors.newFixedThreadPool(2);
        MyRunnable r=new MyRunnable();
        pool.submit(r);

    }
}
class  MyRunnable  implements  Runnable{
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            System.out.println(Thread.currentThread().getName()+ i);
        }
    }
}

 

 

 

 

 

 

上一篇:Java线程使用


下一篇:Django的 select_related 和 prefetch_related 函数对 QuerySet 查询的优化(一)