java多线程1-如何创建线程

来源:互联网 发布:淘宝总部投诉客服电话 编辑:程序博客网 时间:2024/06/04 19:07

       线程可以认为是一条计算机执行代码的线索,CPU将按着这条线索去一行一行的执行代码。一般情况下我们的程序从main方法开始执行,也是说只有一个main线程,这样的话我们就只能一次做一件事,而多线程的出现,特别是在多CPU电脑出现之后,就可以让不同的CPU同时执行不同的线程,去做不同的事情。特别是像web server基本都是多线程的,也就是可以同时执行一个请求,并能不断的接受新的请求。

       在java中创建线程有两种方式,一种是通过继承Thread类,并覆盖他的run()方法,一种是在创建Thread对象的时候将一个Runnable对象传递给他。以下是两种方式的demo

(一)继承Thread类

public static void main(String[] args){       //thread1       new Thread(){           @Override           public void run() {               while(true){                   System.out.println(Thread.currentThread().getName());                   try {                       Thread.sleep(1000);                   } catch (InterruptedException e) {                       e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.                   }               }           }       }.start();       //thread2       new Thread(){           @Override           public void run() {               while(true){                   System.out.println(Thread.currentThread().getName());                   try {                       Thread.sleep(1000);                   } catch (InterruptedException e) {                       e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.                   }               }           }       }.start();   }
(二)传递Runnable对象给Thread的构造方法

public static void main(String[] args){       //thread1       new Thread(new Runnable() {           @Override           public void run() {               while(true){                   System.out.println(Thread.currentThread().getName());                   try {                       Thread.sleep(1000);                   } catch (InterruptedException e) {                       e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.                   }               }           }       }).start();       //thread2       new Thread(new Runnable() {           @Override           public void run() {               while(true){                   System.out.println(Thread.currentThread().getName());                   try {                       Thread.sleep(1000);                   } catch (InterruptedException e) {                       e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.                   }               }           }       }).start();   }

一般来说第二种方式使用较多,一是因为java的单继承导致很多情况下不能通过继承Thread类来创建线程,另一个原因是第二种更符合面向对象的思想。

以上就是创建线程的两种方法,如果你觉得都OK了,请看下下面的代码会输出什么样的结果?

public static void main(String[] args){      new Thread(new Runnable() {          @Override          public void run() {              System.out.println("runnable");          }      }){          @Override          public void run() {              System.out.println("sub class");          }      }.start();   }