首頁 > Java > java教程 > 主體

java中多線程的一些基本方法的使用介紹(附範例)

不言
發布: 2018-10-08 15:12:34
轉載
2386 人瀏覽過

本篇文章帶給大家的內容是關於java中多線程中的一些基本方法的使用介紹(附示例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

線程睡眠sleep()

Thread.sleep(毫秒);我們可以透過sleep方法設定讓線程睡眠。可以看到sleep是個靜態方法

public static native void sleep(long var0) throws InterruptedException;
登入後複製
    try {
        System.out.println(new Date().getSeconds());
        Thread.sleep(5000);
        System.out.println(new Date().getSeconds());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
登入後複製

setDaemon守護線程

非守護線程停止,那麼守護線程自動退出

    public static void main(String[] args) {
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                super.run();
                for(int i = 0; i < 5; i ++) {
                    System.out.println("非守护线程");
                }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for(int i = 0; i < 200; i ++) {
                    System.out.println("守护线程");
                }
            }
        };

        thread2.setDaemon(true);
        thread1.start();
        thread2.start();
    }
登入後複製

可以很明顯的看到thread2本來應該執行200次輸出,但是這裡只輸出了幾行。因為當thread1執行完畢後,thread2作為守護線程就自動停止了。
java中多線程的一些基本方法的使用介紹(附範例)

多線程jion

如果執行了jion方法,那麼就停止當前線程,先跑執行了jion()的線程。相當於插隊執行。如下,在執行thread2執行緒的時候,如果i==20的時候,則讓thread1插隊先執行

    public static void main(String[] args) {
        final Thread thread1 = new Thread() {
            @Override
            public void run() {
            super.run();
            for(int i = 0; i < 500; i ++) {
                System.out.println("thread1---" + i);
            }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for(int i = 0; i < 200; i ++) {
                    if (i == 20) {
                        try {
                            //插队执行
                            thread1.join();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(i);
                }
            }
        };
        thread1.start();
        thread2.start();
    }
登入後複製

join()方法也可以傳參數long 毫秒join(毫秒)
表示讓執行join的線程,插隊執行XXX毫秒,過了時間後,兩個線程交替執行

   public static void main(String[] args) {
        final Thread thread1 = new Thread() {
            @Override
            public void run() {
            super.run();
            for(int i = 0; i < 500; i ++) {
                System.out.println("thread1---" + i);
            }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for(int i = 0; i < 200; i ++) {
                    if (i == 20) {
                        try {
                            //插队执行1毫秒
                            thread1.join(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(i);
                }
            }
        };
        thread1.start();
        thread2.start();
    }
登入後複製

yeild 禮讓線程

yeild會讓出cpu,讓其他線程執行

    public static void main(String[] args) {
        final Thread thread1 = new Thread() {
            @Override
            public void run() {
            super.run();
            for(int i = 0; i < 500; i ++) {
                System.out.println( getName() + "---" + i);
            }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for(int i = 0; i < 200; i ++) {
                    if (i % 5 == 0) {
                        Thread.yield();
                    }
                    System.out.println(getName() + "---" + i);
                }
            }
        };
        thread1.start();
        thread2.start();
    }
登入後複製

setPriority給執行緒設定優先權

預設優先權是5 最小1,最大10
越大優先權越高

    public static void main(String[] args) {
        final Thread thread1 = new Thread() {
            @Override
            public void run() {
            super.run();
            for(int i = 0; i < 500; i ++) {
                System.out.println( getName() + "---" + i);
            }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for(int i = 0; i < 500; i ++) {

                    System.out.println(getName() + "---" + i);
                }
            }
        };
        //设置最大的线程优先级最大为10
        thread1.setPriority(Thread.MIN_PRIORITY);
        //设置最小的线程优先级,最小为1
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();
    }
登入後複製

synchronized

同步程式碼區塊

當多執行緒並發,多段程式碼同時執行的時候。希望在執行其中程式碼的時候,cpu不切換執行緒

不用synchronized的情況

我們來看一下不用synchronized的情況會發生什麼

public class ThreadSynchronied {

    public static void main(String[] args) {
        final Say say = new Say();

         Thread thread1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0 ; i < 10000 ; i ++) {
                    say.say();
                }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0 ; i < 10000 ; i ++) {
                    say.say1();
                }
            }
        };
        //设置最大的线程优先级最大为10
        thread1.setPriority(Thread.MIN_PRIORITY);
        //设置最小的线程优先级,最小为1
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();
    }
}

class Say {
    void say() {
        System.out.print("s ");
        System.out.print("a ");
        System.out.print("y ");
        System.out.print("h ");
        System.out.print("e ");
        System.out.print("l ");
        System.out.print("l ");
        System.out.println("o");
    }

    void say1() {
        System.out.print("1 ");
        System.out.print("2 ");
        System.out.print("3 ");
        System.out.print("4 ");
        System.out.print("5 ");
        System.out.print("6 ");
        System.out.print("7 ");
        System.out.println("8");
    }
}
登入後複製

java中多線程的一些基本方法的使用介紹(附範例)

我們發現有些輸出並沒有印出全,在執行緒thread1的過程中,cpu被thread2搶佔。這種情況下,肯定是不符合我們的業務邏輯的。所以我們要確保執行緒執行了一個完整的方法後,cpu才會被其他執行緒搶佔

使用synchronized

public class ThreadSynchronied {

    public static void main(String[] args) {
        final Say say = new Say();

         Thread thread1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0 ; i < 10000 ; i ++) {
                    say.say();
                }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0 ; i < 10000 ; i ++) {
                    say.say1();
                }
            }
        };
        //设置最大的线程优先级最大为10
        thread1.setPriority(Thread.MIN_PRIORITY);
        //设置最小的线程优先级,最小为1
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();
    }
}

class Say {
    String s = "hahaah";

    void say() {
        synchronized (s) {
            System.out.print("s ");
            System.out.print("a ");
            System.out.print("y ");
            System.out.print("h ");
            System.out.print("e ");
            System.out.print("l ");
            System.out.print("l ");
            System.out.println("o");
        }
    }

    void say1() {
        synchronized (s) {
            System.out.print("1 ");
            System.out.print("2 ");
            System.out.print("3 ");
            System.out.print("4 ");
            System.out.print("5 ");
            System.out.print("6 ");
            System.out.print("7 ");
            System.out.println("8");
        }
    }
}
登入後複製

java中多線程的一些基本方法的使用介紹(附範例)

使用synchronized同步程式碼區塊後,就發現不會出現上述情況了

同步方法

public class ThreadSynchroniedMethod {

    public static void main(String[] args) {
        final Say say = new Say();

         Thread thread1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0 ; i < 10000 ; i ++) {
                    say.say();
                }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0 ; i < 10000 ; i ++) {
                    say.say1();
                }
            }
        };
        //设置最大的线程优先级最大为10
        thread1.setPriority(Thread.MIN_PRIORITY);
        //设置最小的线程优先级,最小为1
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();
    }
}

class Say {
    //在方法上加锁
    static synchronized void say() {
            System.out.print("s ");
            System.out.print("a ");
            System.out.print("y ");
            System.out.print("h ");
            System.out.print("e ");
            System.out.print("l ");
            System.out.print("l ");
            System.out.println("o");

    }

     static void say1() {
        synchronized (Say.class) {
            System.out.print("1 ");
            System.out.print("2 ");
            System.out.print("3 ");
            System.out.print("4 ");
            System.out.print("5 ");
            System.out.print("6 ");
            System.out.print("7 ");
            System.out.println("8");
        }
    }
}
登入後複製

同步方法指的就是在方法上加鎖

#靜態同步方法的所物件是該類別的字節碼物件
非靜態的同步方法鎖定物件是this

多個執行緒使用相同資源鎖,容易造成死鎖

什麼是死鎖?

#死鎖是指兩個或兩個以上的進程在執行過程中,由於競爭資源或由於彼此通信而造成的一種阻塞的現象,若無外力作用,它們都將無法推進下去。此時稱系統處於死鎖狀態或系統產生了死鎖,這些永遠在互相等待的進程稱為死鎖進程。

線程安全類別

Vector
StringBuffer
HashTable

線程不安全

ArrayList
StringBuilder
# HashSet

java.util.Collections中有synchronizedList等方法,支援我們把執行緒不安全的集合轉成線程安全的
java中多線程的一些基本方法的使用介紹(附範例)

#

以上是java中多線程的一些基本方法的使用介紹(附範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:cnblogs.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!