線程的五大狀態及常用方法


線程的五大狀態

  1. 創建--new Thread()
  2. 就緒--調用start()
  3. 阻塞--sleep()、wait()
  4. 運行--CPU調度
  5. 死亡--線程中斷或結束,一旦進入死亡狀態,就不能再次啟動

線程的基本方法

線程stop方法

package com.edgar.lesson03;
//測試stop方法
//1.建議線程正常停止--->利用次數,不建議死循環
//2.建議使用標志位--->設置一個標志位
//3.不要使用stop或者destory等過時或者jdk不建議使用的方法
public class TestStop implements Runnable {

    //1.設置一個標志位
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while (flag) {

            System.out.println("run...thread" + i++);
        }
    }


    //2.設置一個公開的方法停止線程,轉換標志位
    public void stop() {
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main"+i);
            if (i == 900) {
                //調用stop方法切換標志位,讓線程停止
                testStop.stop();
                System.out.println("線程該停止了");
            }
        }
    }
}

線程休眠sleep()

package com.edgar.lesson03;

import java.text.SimpleDateFormat;
import java.util.Date;
//線程休眠
//模擬倒計時
public class TestSleep {

    public static void main(String[] args) {

        //打印當前系統時間
        Date date = new Date(System.currentTimeMillis());
        while(true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
                date = new Date(System.currentTimeMillis());//更新當前時間
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

    public static void tendown() throws InterruptedException {
        int num=10;
        while(true){
            Thread.sleep(1000);
            System.out.println(num--);
            if(num<=0){
                break;
            }
        }

    }
}

線程禮讓yeild()

package com.edgar.lesson03;

//線程禮讓
//禮讓不一定成功,看CPU心情
public class TestYield {

    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }
}
class MyYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"線程開始");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"線程結束");
    }
}

線程強行執行jion()

package com.edgar.lesson03;
//線程強行執行
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("線程"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        for (int i = 0; i < 1000; i++) {
            if(i==200){
                thread.join();
            }
            System.out.println("主線程"+i);

        }
    }
}

線程優先級setPriority()

package com.edgar.lesson03;
//線程的優先級
//優先級高不一定先執行,看CPU心情
public class TestPriority {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();

        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);

        t1.start();

        t2.setPriority(3);
        t2.start();

        t3.setPriority(7);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);
        t4.start();



    }
}

class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    }
}

測試線程的狀態getState()

package com.edgar.lesson03;
//觀察測試線程的狀態
public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("///////////");
        });

        Thread.State state = thread.getState();
        System.out.println(state);//NEW

        thread.start();//啟動線程
        state = thread.getState();
        System.out.println(state);//RUNNABLE

        while(state!=Thread.State.TERMINATED){
            Thread.sleep(100);
            state = thread.getState();//更新狀態
            System.out.println(state);
        }



    }
}

守護線程setDaemon()

package com.edgar.lesson03;

//守護線程:gc()、main()
public class TestDaemon {

    public static void main(String[] args) {
        God god = new God();
        You you = new You();
        Thread thread = new Thread(god);
        Thread thread2 = new Thread(you);//用戶線程
        thread.setDaemon(true);//設置守護線程
        thread.start();
        thread2.start();
    }
}
class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("上帝保佑着你");
        }
    }
}

class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("永遠開心的活着");
        }
        System.out.println("你結束了生命!!");
    }
}

高並發場景

多個線程對同一個資源進行操作會出現高並發場景


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM