Java多線程實現

來源:互聯網
上載者:User

標籤:

    在Java中實現多線程有2種方法:

1.繼承Thread

public class ThreadDemo extends Thread {    String name;    private  int count = 100;    // 使用Thread類的有參數的建構函式    ThreadDemo(String name) {        this.name = name;    }    public void run() {        // compute primes larger than minPrime        for (int i = 0; i < 100; i++) {                calcCount();                System.out.println("線程開始:" + this.name + ",i=" + i + ",count="                        + count);        }        // System.out.println(name);    }    private synchronized void calcCount() {        if (count > 0) {            count--;        }    }    public static void main(String[] args) {        ThreadDemo td = new ThreadDemo("1");        ThreadDemo td2 = new ThreadDemo("2");        ThreadDemo td3 = new ThreadDemo("3");        td.start();        td2.start();        td3.start();    }}

 

2.實現Runnable介面

public class RunnableDemo implements Runnable{    String name;    RunnableDemo(String name) {         this.name=name; }            @Override    public void run() {        // TODO Auto-generated method stub         for(int i=0;i<100;i++){               System.out.println("線程開始:"+this.name+",i="+i);               }      }        public static void main(String[] args){        RunnableDemo rd=new RunnableDemo("1");        RunnableDemo rd2=new RunnableDemo("2");        RunnableDemo rd3=new RunnableDemo("3");        new Thread(rd,"ww").start();        new Thread(rd2).start();        new Thread(rd3).start();    }}

 這兩種方式都可以正常完成多線程的處理,網上講述:一般情況下使用多線程是用業務類實現Runnable介面。

看下Thread的定義:

public class Thread implements Runnable{...}

我們就知道Thread其實就是Java裡面對Runnable的官方實現,如果我們不需要特別的控制的話,直接用Thread就可以了。

情況有點類似List的實現,我們在Java中用ArrayList就可以了,當然你也可以自訂一個List的實作類別出來。。。。

 

資源同步

使用多線程就不得不提到線程同步,為了訪問有限資源,對資源上鎖是一件必須的操作步驟。當然上鎖也是一件耗費系統資源的事情,需要在開發時做一些取捨。

常用上鎖方法有 synchronized 、lock,可以簡單認為是自動化和手工處理的差別。

對同步講的較多的是:http://www.cnblogs.com/devinzhang/archive/2011/12/14/2287675.html

 

Java多線程實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.