JAVA多線程(一)

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 0
Result of 1
Result of 2
Result of 3
task[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 awakened
joiner 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對象,就可以達到我們的目的了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章