多線程的一些小Demo,多線程Demo

來源:互聯網
上載者:User

多線程的一些小Demo,多線程Demo
一、多個線程單個鎖

package com.sun.multithread.sync;public class MyThread extends Thread {    private int count = 5;        // synchronized加鎖    public synchronized void run() {        count--;        System.out.println(this.currentThread().getName() + " count = " + count);    }        public static void main(String[] args) {                MyThread myThread = new MyThread();        Thread t1 = new Thread(myThread, "t1");        Thread t2 = new Thread(myThread, "t2");        Thread t3 = new Thread(myThread, "t3");        Thread t4 = new Thread(myThread, "t4");        Thread t5 = new Thread(myThread, "t5");                t1.start();        t2.start();        t3.start();        t4.start();        t5.start();    }}
二、多個線程多把鎖
package com.sun.multithread.sync;public class MultiThread {        private static int num = 0;        /**     * 在靜態方法上加synchronized關鍵字,表示鎖定class類,類層級的鎖     * 關鍵字synchronized取得的鎖都是對象鎖,而不是把一段代碼(方法)當成鎖,     * 所以代碼中哪個線程先執行synchronized關鍵字的方法,哪個線程就持有該方法所屬對象的鎖     *      * @param tag 參數     */    public static synchronized void printNum(String tag){        try {            if(tag.equals("a")){                num = 100;                System.out.println("tag a, set num over!");                Thread.sleep(1000);            } else {                num = 200;                System.out.println("tag b, set num over!");            }            System.out.println("tag " + tag + ", num = " + num);        } catch (InterruptedException e) {            e.printStackTrace();        }    }        public static void main(String[] args) {        // 兩個不同的對象        final MultiThread m1 = new MultiThread();        final MultiThread m2 = new MultiThread();                Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                m1.printNum("a");            }        });                Thread t2 = new Thread(new Runnable() {            @Override            public void run() {                m1.printNum("b");            }        });                t1.start();        t2.start();    }}

 

聯繫我們

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