搜尋
首頁Javajava教程java中多線程的一些基本方法的使用介紹(附範例)

本篇文章帶給大家的內容是關於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中文網其他相關文章!

陳述
本文轉載於:博客园。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境