java 多線程編程

來源:互聯網
上載者:User

標籤:啟用   static   覆蓋   void   oid   包括   []   程式   extends   

一.關於線程

  • 線程是執行java程式碼的基本單位
  • java線程是java平台的一部分

二.java中的線程編程

Thread類

java中的線程已被封裝為Thread類,void start()方法就是啟動線程的方法,調用後會讓線程去執行指定的方法。void run()是其中一個方法,start()方法會把它作為線程的起點。

只要讓一個類去繼承Thread類,然後去覆蓋其中的run()方法,那麼就可以控制線程了

 1 public class UseThread{ 2         public static void main(String[] args){ 3             MyThread thread = new MyThread(); 4             thread.run; 5         } 6 } 7 class MyThread extends Thread{ 8     public void run(){ 9         System.out.println("This is a thread code");10     }11 }

 

 可是一個類只能實現單繼承,如果繼承了線程類後,則無法繼承其它類,於是這時候最好是使用介面。java提供了Runnable()介面,它包括了run()方法在內。Thread類中含有Runnable屬性,構造方法可以是Thread(Runnable),只要Runnable不為null,那麼就可以啟用run()方法。

public class UseThread {
    public static void main(String[] args){ MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.run(); }}class MyRunnable implements Runnable{ public void run(){ System.out.println("這是一個線程代碼"); }}

 

package study_java;public class Inner {        public static void main(String[] args){            PrintCurrentThread printer = new PrintCurrentThread();            //匿名內部類            Runnable runnable = new Runnable(){                public void run(){                    PrintCurrentThread p = new PrintCurrentThread();                    p.printcurrrentthread();                }            };            Thread thread = new Thread(runnable,"線程-1");            thread.start();                        printer.printcurrrentthread();        }}class PrintCurrentThread{    public void printcurrrentthread(){        Thread currentthread = Thread.currentThread();        String threadname = currentthread.getName();        System.out.println(threadname);            }}

 

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.