多线程学习笔记(2)----------Thread的一些常用方法

目录

一、线程停止

二、线程睡眠Thread.sleep()

三、线程礼让 Thread.yield()

四、线程强制执行join

五、线程状态监测 Thread.getState()

六、线程优先级

七、守护线程


一、线程停止

package com.daiy.demo7;

/**
 * 测试线程停止
 * 1、建议线程正常停止----利用次数,不建议死循环
 * 2、建议使用标志位-----设置一个标志位
 * 不要使用stop或者destroy等过时或者jdk不建议使用的方法
 */
public class TsetStop implements Runnable{
    //1、设置一个标志位
    private boolean flag=true;

    @Override
    public void run() {
        int n=0;
        while (flag){
            System.out.println("线程正在跑】】】】"+n++);
        }

    }

    //2、设置一个停止线程的方法,转换标志位
    public void newStop(){
        this.flag=false;
    }

    public static void main(String[] args) {

        TsetStop tsetStop = new TsetStop();
        new Thread(tsetStop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main方法>>>>"+i);
            if(i==900){
                //停止线程
                tsetStop.newStop();
                System.out.println("线程要停止了------");
            }
        }
    }

}

 

二、线程睡眠Thread.sleep()

package com.daiy.demo8;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestSleep {

    private static int count = 10;

    public static void main(String[] args) {

        try {
            countDown();//线程睡眠实现倒计时
            nowTime();//线程睡眠实现当前时间显示
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //倒计时
    public static void countDown() throws InterruptedException {
        while (true) {
            System.out.println(count--);
            Thread.sleep(1000);
            if (count <= 0) {
                break;
            }
        }
    }

    public static void nowTime() throws InterruptedException {
        Date date = new Date(System.currentTimeMillis());//当前系统时间
        while (true) {
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
            date = new Date(System.currentTimeMillis());//当前系统时间
        }
    }

}

 

三、线程礼让 Thread.yield()

package com.daiy.demo8;

/*测试礼让线程
 *礼让不一定成功,看CPU
 */
public class TestYield {
    public static void main(String[] args) {
        ThreadYield threadYield = new ThreadYield();
        new Thread(threadYield, "a线程").start();
        new Thread(threadYield, "b线程").start();
    }
}

class ThreadYield implements Runnable {

    @Override
    public void run() {

        System.out.println(Thread.currentThread().getName() + "线程开始执行了");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + "线程结束了");
    }
}

 

四、线程强制执行join

package com.daiy.demo8;

public class TestJoin implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i < 5; 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 = 1; i < 10; i++) {
            System.out.println("主线程main--->" + i);
            if (i == 3) {
                thread.join();
            }
        }

    }
}

 

五、线程状态监测 Thread.getState()

  • 线程状态。 线程可以处于以下状态之一:
    • NEW
      尚未启动的线程处于此状态。
    • RUNNABLE
      在Java虚拟机中执行的线程处于此状态。
    • BLOCKED
      被阻塞等待监视器锁定的线程处于此状态。
    • WAITING
      正在等待另一个线程执行特定动作的线程处于此状态。
    • TIMED_WAITING
      正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
    • TERMINATED
      已退出的线程处于此状态。

 

package com.daiy.demo8;

//线程状态
public class TestState implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
                System.out.println("^^^^^^^^^^^^^^^^^^^^" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("线程跑完了");
    }


    public static void main(String[] args) throws InterruptedException {
        TestState testState = new TestState();
        Thread thread = new Thread(testState);
        //观察线程新建时状态
        Thread.State state = thread.getState();
        System.out.println("线程新建时状态:" + state);

        thread.start();
        state = thread.getState();
        System.out.println("线程启动时状态:" + state);

        while (state != Thread.State.TERMINATED) {//只要线程不终止,就一直输出线程状态
            Thread.sleep(100);
            state = thread.getState();
            System.out.println("线程当前状态:" + state);
        }

    }
}

 

六、线程优先级

package com.daiy.demo8;

//线程优先级测试,大小位1到10
//优先级低只是意味着获得调度的概率低,并不是优先级低就一定会后备调用,主要还是看CPU调度
public class TestPriority {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

        MyPrioriy myPrioriy = new MyPrioriy();

        Thread thread1 = new Thread(myPrioriy, "线程一");
        Thread thread2 = new Thread(myPrioriy, "线程二");
        Thread thread3 = new Thread(myPrioriy, "线程三");
        Thread thread4 = new Thread(myPrioriy, "线程四");
        Thread thread5 = new Thread(myPrioriy, "线程五");

        thread1.start();//默认为5


        thread2.setPriority(6);
        thread2.start();

        thread3.setPriority(1);
        thread3.start();

        thread4.setPriority(Thread.MAX_PRIORITY);//最大值 10
        thread4.start();

        thread5.setPriority(8);
        thread5.start();


    }
}

class MyPrioriy implements Runnable {

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

    }
}

 

七、守护线程

package com.daiy.demo8;

/**
 * 1、线程分为用户线程和守护线程
 * 2、虚拟机确保用户线程执行完毕,但不用等待守护线程执行完毕
 */
public class TestDaemon {

    public static void main(String[] args) {
        Parents parents = new Parents();
        Child child = new Child();
        Thread threadParents = new Thread(parents);
        threadParents.setDaemon(true);//设置为守护线程,默认为false表示用户线程
        threadParents.start();

        new Thread(child).start();

    }
}

class Parents implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("父母一直守护着孩子!");
        }
    }
}

//孩子们
class Child implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 50000; i++) {
            System.out.println("孩子们生活着--------------------->" + i);
        }
        System.out.println("**************************************************");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值