JAVA學習筆記(四十一)-多線程與線程組

來源:互聯網
上載者:User

標籤:多線程   線程組   

線程組ThreadGroup
/* * 線程組ThreadGroup *  * 結論: * 如果在設定線程組優先順序之前設定線程優先順序,則線程優先順序不受線程組優先順序限制 * 如果在設定線程組優先順序之後設定線程優先順序,則線程優先順序不能超過線程組優先順序 *  * 線程的優先順序,預設與啟動它的父線程相同,但受到所有線程組的限制 */public class Test02 {    public static void main(String[] args) {        System.out.println(Thread.currentThread().getName() + "線程,所屬線程組:"                + Thread.currentThread().getThreadGroup());        System.out.println(Thread.currentThread());        Thread.currentThread().setPriority(8);        Thread th=new Thread("mythread");        System.out.println(th.getPriority());        // 定義一個線程組tg        ThreadGroup tg = new ThreadGroup("wbs14061線程組");        System.out.println("tg線程組的父線程組:"+tg.getParent());        //建立線程一,屬於tg線程組        Thread th1=new Thread(tg, new MyThread2(), "first");        Thread th2=new Thread(tg, new MyThread2(), "second");        th1.setPriority(8);        tg.setMaxPriority(4);        th2.setPriority(9);        Thread th3=new Thread(tg, new MyThread2(), "third");        System.out.println("tg線程組的資訊:"+tg);        th1.start();        th2.start();        th3.start();        //tg.stop();    }}class MyThread2 implements Runnable {    int num = 1;    @Override    public void run() {        while (num <= 100) {            System.out.println(Thread.currentThread().getName() + ","                    + Thread.currentThread().getPriority() + "****" + num++);        }    }}
多線程訪問共用資料
/* *  多線程訪問共用資料 *   *  多線程操作共用資料可能會出現問題,即安全執行緒問題 *  原因:當多個線程操作共用資料時,一個線程只執行了部分語句,還沒執行完,此時CPU時間片切換了,另一個線程參與進來,導致共用資料的錯誤 *  解決:同步機制synchronized *   *  同步的前提: *  1.必須要有兩個或者兩個以上的線程 *  2.必須是多個線程使用同一個鎖 *   *  保護範圍: *  1.只將需要的代碼添加到synchronized塊中 *  2.不要將run()方法中所有的代碼都添加到synchronized塊中,否則相當於單線程 *   *  線程同步的優缺點: *  優點:解決了安全執行緒 *  缺點:由於多個線程需要進行鎖的判斷,消耗資源,導致效率降低 */public class Test03 {    public static void main(String[] args) {        Ticket ticket = new Ticket();        Thread th1 = new Thread(ticket, "線程1");        Thread th2 = new Thread(ticket, "線程2");        Thread th3 = new Thread(ticket, "線程3");        th1.start();        th2.start();        th3.start();    }}class Ticket implements Runnable {    private int num = 100; // 總共100張票,共用此資料    Object obj = new Object();    @Override    public void run() {        while (true) {            // 關鍵代碼塊,保護共用資料的安全            synchronized (obj) {                if (num > 0) {                    try {                        Thread.sleep(10);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    System.out.println(Thread.currentThread().getName()                            + "售出車票:" + num--);                }            }        }    }}
synchronized 方法
/* * 使用synchronized修改方法,稱為同步方法(同步函數),安全執行緒的 *  * 同步函數使用的鎖是當前對象,即this鎖 * 靜態同步函數使用的鎖是位元組碼檔案對象 */public class Test04 {    public static void main(String[] args) {        Account account=new Account();        Thread th1=new Thread(account, "你爸");        Thread th2=new Thread(account, "你媽");        th1.start();        th2.start();    }}/* * 銀行賬戶類 */class Bank {    private double balance;// 餘額    // 查看餘額    public void getBalance() {        System.out.println("當前餘額:" + balance);    }    // 存錢    public void setBalance(double money) {        balance = balance + money;    }}/* * 兩個人同時往一個賬戶裡打錢,每次打300元,總共打3次,合計900元 */class Account implements Runnable {    private static Bank bank = new Bank();    static int i = 1;    @Override    public void run() {        while (true) {            saveMoney();        }    }    //同步函數,同一時間只能有一個線程執行此函數    public static synchronized void saveMoney(){        if (i <= 3) {            try {                Thread.sleep(10);//休眠10ms,打錢次數會異常            } catch (InterruptedException e) {                e.printStackTrace();            }            bank.setBalance(300);            System.out.println(Thread.currentThread().getName()                    + "存了300元,第" + (i++) + "次");            bank.getBalance();// 列印當前餘額        } else {            System.exit(0);        }    }}

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.