JAVA線程應用Thread

來源:互聯網
上載者:User

標籤:public   java   start   

java線程學習:

    基本概念:

當一個程式開啟的時候,會啟動一個進程,在進程中會開啟線程,如果只有一個線程,這個線程就稱為主線程。如果進程停止,會先殺死線程再退出!

    java線程類:Thread 
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/6F/62/wKiom1WahB7BIfLkAAEEbMlxEcM761.jpg" title="Thread詳解圖" alt="wKiom1WahB7BIfLkAAEEbMlxEcM761.jpg" />

方法的作用:

如:start()方法啟用線程,調用run方法啟動進程。

//定義線程類名;繼承Thread類

class Demo extends Thread

{

//複寫Runnable 的run方法;

public void run()

{

for(int x=0;x<60;x++)

{

System.out.println("線程啟動"+x);

}

}

}




//定義主函數類名

class  ThreadDemo

{

public static void main(String[] args) 

{

//定義Demo類對象;

Demo d = new Demo();

Demo d1 = new Demo();

//調用Runnable的start方法啟動線程;

d.start();

d1.start();

for(int x=0;x<60;x++)

{

System.out.println("Hello Thread!"+x);

}

}

}


線程都有預設名稱編號,該編號從0開始;

通過getName()方法擷取

class Test extends Thread

{

//private String name;

Test(String name)

{

//this.name=name;

    super(name);

}

public void run()

{

for(int x=0;x<50;x++)

{

System.out.println(this.getName()+"...........Run Thread.........."+x);

}

}

}




class ThreadTest 

{

public static void main(String[] args) 

{

Test t1 = new Test("HHHHH");

Test t2 = new Test("XXX");

t1.start();

t2.start();

}

}



 sleep(time自訂)方法:當一個線程遇上該方法則暫停執行;等待時間完成再執行。

 wait()方法

 stop()方法

本文出自 “飛翔的蠍子” 部落格,請務必保留此出處http://tanglongwei.blog.51cto.com/4411684/1671461

JAVA線程應用Thread

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.