JAVA多线程(一)

来源:互联网 发布:淘宝沟通软件 编辑:程序博客网 时间:2024/05/16 05:17
Java多线程基础
1、实现线程的方式
  在Java中线程的实现无外乎两种方法:实现Runnable接口、继承Thread类:
  实现Runnable接口
public class MyTask implements Runnable{    @Override    public void run()    {        System.out.println("mytask executed....");    }    public static void main(String[] args)    {        Thread t = new Thread(new MyTask());        t.start();        System.out.println("main complete.");    }}

  继承Thread类
public class MyTask2 extends Thread{    @Override    public void run()    {        System.out.println("mytask2 executed....");    }        public static void main(String[] args)    {        Thread t = new MyTask2();        t.start();        System.out.println("main complete.");    }}

2、实现线程的变种方式
  Java的线程的实现方式还有很多变种,但都是基于上面的两种 方式的。
  使用内部类继承Thread类
public class InnerThread  {      private Inner inner;            private class Inner extends Thread      {          @Override        public void run()          {              System.out.println("inner task executed....");          }      }        public InnerThread()      {          inner = new Inner();        inner.start();    }            public static void main(String[] args)      {          InnerThread i = new InnerThread();          System.out.println("main complete.");      }  }

  使用匿名内部类
public class AnonymousThread{    public AnonymousThread()    {        Thread t = new Thread(){            @Override            public void run()            {                System.out.println("anonymous task executed....");            }        };                t.start();    }        public static void main(String[] args)    {        AnonymousThread i = new AnonymousThread();        System.out.println("main complete.");    }}

  以上两个变种都是使用了Thread类,当然也可以使用Runnable接口,做法类似,在此就不举例子了。
3、Executors
  Java1.5引入了一些新的类,方便了对线程的管理,先看下面的例子
public class CachedThreadPool{    public static void main(String[] args)    {        ExecutorService exec = Executors.newCachedThreadPool();        for (int i=0; i<5; i++)        {            exec.execute(new MyTask());        }        exec.shutdown();        System.out.println("main complete.");    }    }class MyTask implements Runnable{      static int counter = 0;    private final int id = counter++;        @Override    public void run()    {        System.out.println("task[" + id + "] executed....");    }}

  在上面的例子中,并没有使用直接使用Thread类的start()方法执行线程,而是交给了Executor来管理线程的执行。

  Executors.newCachedThreadPool()方法创建一个ExecutorService(一个Executor的实现),Executor会为每个需要执行的任务创建一个线程并执行它;当Executor的shutdown()方法被调用后,就不能再把任务提交给Executor了,否则会报java.util.concurrent.RejectedExecutionException异常。

  除了CachedThreadPools,还有FixedThreadPools和SingleThreadExecutor。三者的区别非常简单,CachedThreadPools根据需要创建足够多的线程;FixedThreadPools在初始化的时候就创建好固定数目的线程;SingleThreadExecutor就像是大小为1的FixedThreadPools,同一时间只会有一个线程在执行。

  从下面的例子就可以看出来当有多个任务提交给SingleThreadExecutor时,这些任务将按照提交的顺序一个一个的执行;同样的道理也适合FixedThreadPools。
public class CachedThreadPool{    public static void main(String[] args)    {        ExecutorService exec = Executors.newSingleThreadExecutor();        for (int i=0; i<5; i++)        {            exec.execute(new MyTask());        }        exec.shutdown();        System.out.println("main complete.");    }    }class MyTask implements Runnable{      static int counter = 0;    private final int id = counter++;        @Override    public void run()    {        System.out.println("task[" + id + "] started....");        Thread.currentThread().yield();        System.out.println("task[" + id + "] completed....");    }}

  输出结果
task[0] started....main complete.task[0] completed....task[1] started....task[1] completed....task[2] started....task[2] completed....task[3] started....task[3] completed....task[4] started....task[4] completed....

  从结果可以看出,交给SingleThreadExecutor管理的任务都是串行执行的。
4、让线程像方法一样返回结果
  线程,是某个任务的一次执行过程,从线程本身来看,它不应该像方法那样具有返回值。但是为了提高程序的灵活性,Java1.5提供了Callable接口,通过Callable接口,可以让线程返回一个值,看下面的例子:
public class CallableDemo{    public static void main(String[] args)    {        ExecutorService exec = Executors.newCachedThreadPool();        List<Future<String>> threadRlt = new ArrayList();                for(int i=0; i<5;i++)        {            threadRlt.add(exec.submit(new MyTask()));        }                for (Future<String> f : threadRlt)        {            try            {                System.out.println(f.get());            }            catch (InterruptedException e)            {                e.printStackTrace();            }            catch (ExecutionException e)            {                e.printStackTrace();            }        }    }}class MyTask implements Callable<String>{    static int counter = 0;    private final int id = counter++;    @Override    public String call()    {        System.out.println("task[" + id + "] started....");        Thread.currentThread().yield();        System.out.println("task[" + id + "] completed....");                return "Result of " + id;    }}

  输出结果
task[0] started....task[1] started....task[0] completed....task[2] started....task[1] completed....task[3] started....task[3] completed....task[2] completed....task[4] started....Result of 0Result of 1Result of 2Result of 3task[4] completed....Result of 4

  从输出结果中,可以看到每个线程的返回值"Result of X"都在main方法中取到并打印到控制台了。

  使用Callable接口时,要注意以下几点:
  • 使用Callable时,要实现的是call()方法,而不是run()方法,并且call()方法是有一个返回值 的;
  • 使用Callable的任务,只能通过Executor.submit()方法来执行,而不能像普通线程那样,通过Thread.start()来启动;
  • Executor.submit()方法返回一个Future对象,通过Future对象的get()方法,可以拿到线程的返回值。如果线程还没有执行结束,那么get()方法会阻塞,一直到线程执行结束。在调用get()方法前,也可以通过isDone方法先判断线程是否已经执行结束。

5、线程的基础知识
  Deamon(后台线程)
  后台线程往往是在运行在后台,给程序提供某些服务的线程,它本身不算是程序的组成部分。所以,当虚拟机中只剩下后台线程时,程序也就自动结束了;但只要还有任何非后台线程在运行着,程序就不会结束。看下面的例子:
public class DaemonThreadDemo{    public static void main(String[] args)    {        Thread t = new Thread() {            @Override            public void run()            {                try                {                    TimeUnit.SECONDS.sleep(1);                    System.out.println("Can u see this?");                }                catch (InterruptedException e)                {                    e.printStackTrace();                }                finally                {                    System.out.println("Can reach here?");                }            }        };                t.setDaemon(true);        t.start();    }}

  上面的程序不会有任何的输出,甚至连finally里面的内容也没有执行,因为线程t被设置成了后台线程,在它睡眠的1秒种时间里,main(非后台)线程已经结束了,这时虚拟机中只剩下后台进程,这样程序也自动结束了,因而看不到线程t的输出。

  sleep & yield
  sleep()方法让线程睡眠一段时间,时间过后,线程才会去争取cpu时间片。
  Java1.5提供了一个新的TimeUnit枚举,让sleep的可读性更好。
  yield()方法让线程主动让出cpu,让cpu重新调度以决定哪个线程可以使用cpu。


  优先级
  优先级,故名思意,决定了一个线程的重要程度。优先级高的线程并不一定总比优先级低的进程先得到处理,而只是机会高一些。
  虽然java提供了10个优先级级别,但是由于各个平台对进程、线程优先级的定义各不相同,在程序中最好只用三个优先级别MAX_PRIORITY,NORM_PRIORITY,and MIN_PRIORITY。

  join
  如果一个线程访问了另一个线程的join()方法,那当前线程就会处于等待状态,直到另一个线程结束。例如:
class Sleeper extends Thread{    public Sleeper()    {        start();    }    public void run()    {        try        {            sleep(2000);        }        catch (InterruptedException e)        {            e.printStackTrace();        }        System.out.println("sleeper has awakened");    }}class Joiner extends Thread{    private Sleeper sleeper;    public Joiner(Sleeper sleeper)    {        this.sleeper = sleeper;        start();    }    public void run()    {        try        {            sleeper.join();        }        catch (InterruptedException e)        {            System.out.println("Interrupted");        }                System.out.println("joiner completed");    }}public class Joining{    public static void main(String[] args)    {        Sleeper sleeper = new Sleeper();        Joiner joiner = new Joiner(sleeper);    }}

  结果输出
sleeper has awakenedjoiner completed

  从输出可以看出,joiner在调用了sleeper.join方法后,就会一直等待,直到sleeper执行完了再继续执行。

6、线程的异常处理
  通常情况下,我们会在run()方法里面进行异常处理。但是如果某些时候,需要在run()方法外面处理异常,该怎么办呢?先看下面的例子:
public class ExceptionThread implements Runnable{    public void run()    {        throw new RuntimeException();    }    public static void main(String[] args)    {        try        {            Thread t = new Thread(new ExceptionThread());            t.start();        }        catch(RuntimeException e)        {            System.out.println("caught");        }    }}

  上面的程序并没有像预期那样输出caught,而是直接把异常抛给了控制台。那怎么样才能在run()方法外面处理异常呢?Java1.5提供了一个接口Thread.UncaughtExceptionHandler,只需要实现uncaughtException(Thread t, Throwable e)方法就可以达到我们的目的了,看下面的例子:
public class ExceptionThread implements Runnable{    public void run()    {        throw new RuntimeException();    }    public static void main(String[] args)    {        Thread t = new Thread(new ExceptionThread());        t.setDefaultUncaughtExceptionHandler(new MyHandler());        t.start();    }}class MyHandler implements Thread.UncaughtExceptionHandler{    @Override    public void uncaughtException(Thread arg0, Throwable arg1)    {        System.out.println("caught");    }}

  通过实现一个Thread.UncaughtExceptionHandler对象,就可以达到我们的目的了。
0 0
原创粉丝点击