java 線程的簡單理解

來源:互聯網
上載者:User

標籤:專案檔   err   nbsp   主函數   static   notifyall   start   notify   art   

     想要實現線程可以繼承Thread也可以實現介面runnable,在類中重寫 run()方法在主函數調用start方法就可以開闢線程。

     對於java對象都有一個wait()和notify()、notifyAll()方法這是線程對這個對象資源的使用順序的調和,在調用這些方法錢必須先使用同步鎖synchronized(對象)將方法用在鎖的裡面就可以了。

     一般來說,調用start()方法後run內的內容結束該線程就自動結束了,但是如果裡面有線程還在等待某對象則通過人物管理器的詳細資料可以看到該進程一直存在,並且導致這個專案檔在myEclipse中無法刪除,這時只要在任務管理中的詳細資料裡將這個程式的進程強制關閉就行了。

下面是我做測試的代碼:


   public class MyThread extends Thread{

    public String li="li123";
    public MyThread(String obj){
        super(obj);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        MyThread a=new MyThread("jiangzhongxi");
        NotifyThread b=a.new NotifyThread();
        a.start();
        b.start();
    }

    public void run(){
        System.out.println("建立一個線程1使用li對象");
        try {
            System.out.println("線程1使用li對象4秒");
            sleep(4000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        synchronized(li){
            li.notifyAll();
            System.out.println("該線程1對li對象的使用完畢,已經通知其餘所有等待的線程"+li.intern());
        }
    }
    
     class NotifyThread extends Thread {  
           
            public void run() {  
                System.out.println("建立一個線程2使用li對象");
                synchronized (li) {  
                    try {
                        System.out.println("線程2等待!li對象");
                        li.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                }  
                System.out.println("線程2結束!");
            }  
        };  
}

 

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.