java線程以及定時任務

來源:互聯網
上載者:User

標籤:style   暫停   blog   imp   方法   優先   system   static   線程   

線程的概念在此不再贅述。

下面介紹三種啟動線程的方式。

1. 繼承Thread
public class ThreadTest extends Thread {    @Override    public void run() {        int i  = 0;        while (i < 10){            i++;            System.out.println("this is Thread thread");        }    }}

調用

ThreadTest threadTest = new ThreadTest();threadTest.start();
2. 實現Runnable介面
public class RunnableTest implements Runnable{    int a;    int b;    public RunnableTest(int a, int b){        this.a = a;        this.b = b;    }    public void run(){        int i = 0;        while (i < 10){            i++;            System.out.println("a:" + a + " b:" +b);        }    }}

調用

RunnableTest threadExtends2 = new RunnableTest(5,6);new Thread(threadExtends).start();
3. 匿名類
Thread t = new Thread(){          public void run(){              int i = 0;              while (i < 10){                  i++;                  System.out.println("this is Inside Thread");             }          }};t.start()

線程常用方法:

1. sleep    線程暫停,睡會再執行。

2. join    加入到當前線程中,若加入,則先執行加入的線程,後執行當前線程。

3. setPriority    設定線程優先順序。

4. yield    臨時暫停。

 

下面介紹一種定時執行任務的方法,用的是TimerTask
public static void main(String args[]){        Timer t = new Timer();        TimerTask timerTask = new TimerTask() {            int i = 0;            @Override            public void run() {                System.out.println(i);                i++;                if (i == 5)                    t.cancel();            }        };        t.scheduleAtFixedRate(timerTask,0,1500);

 

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.