【Java基础】线程方法

start():启动线程,使线程进入就绪状态。
run():线程执行的代码逻辑,需要重写该方法。

停止线程

void interrupt() 中断线程,让它重新去争抢cpu
如果目标线程长时间等待,则应该使用interrupt方法来中断等待(强制打断,会发生中断异常InterruptedException)

static void yield() 暂停当前正在执行的线程对象,并执行其他线程

不推荐使用JDK提供的stop()、destroy()方法【已废弃】。推荐线程自己停下来,建议使用一个标志位进行终止变量,当flag=false,则终止线程运行。

package com.shan.demo7;
//测试stop
//1.建议线程正常停止————利用次数,不建议死循环
//2.建议使用标志位————设置一个标志位
//3.不要使用stop或者destroy等过时或者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 mystop(){
        this.flag=false;
    }
    public static void main(String[] args) throws InterruptedException {
        TestStop testStop=new TestStop();
        new Thread(testStop).start();
        Thread.sleep(20);
        int i=0;
        while(true) {
            //System.out.println("main"+i++);
            // 主线程没有其他任务时,运行速度很快,
            // 很容易出现新建的线程启动后,还没有抢到CPU,
            // 没有运行过,程序就已经停止运行的情况
            // 我们可以让主线程休眠,或添加其他任务,
            // 来观看中止线程的效果
            i++;
            if (i==10){
                //调用stop方法切换标志位,让线程停止
                testStop.mystop();
                break;
            }
        }
    }
}

线程休眠

static void sleep(long millis) 让当前正在执行的线程休眠的毫秒数;
sleep存在异常InterruptedException;
sleep时间到达后线程进入就绪状态;
sleep可以模拟网络延时、倒计时等。
每一个对象都有一个锁,sleep不会释放锁。

//模拟网络延时:放大问题的发生性
public class TestSleep implements Runnable {
    private int ticketNums=10;//票数
    @Override
    public void run() {
        while (true){
            synchronized (this) {
                if (ticketNums <= 0) 
                    break;
          		 System.out.println(Thread.currentThread().getName() + "———拿到了第" + ticketNums-- + "张票");
            }
            try {
                Thread.sleep(100);//模拟延时
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        TestSleep ticket=new TestSleep();
        new Thread(ticket,"小明").start();
        new Thread(ticket,"笑笑").start();
        new Thread(ticket,"淘气").start();
    }
}
//模拟倒计时
public class TestSleep2 {
    //模拟倒计时
    public static void tenDown() throws InterruptedException{
        int num=10;
        while(true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num<=0)
                break;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        tenDown();
}
public class TestSleep2 { //打印当前时间
    public static void main(String[] args) throws InterruptedException {
        Date startTime=new Date(System.currentTimeMillis());//获取系统当前时间
        while(true){
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
            Thread.sleep(1000);
            //更新系统当前时间
            startTime=new Date(System.currentTimeMillis());
        }
    }
}

线程礼让

**void yield() ** 礼让不一定成功,得看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()+"线程停止执行");
    }
}
* 礼让成功: 		 * 礼让不成功:
* a线程开始执行		* a线程开始执行
* b线程开始执行  	    * a线程停止执行
* a线程停止执行	    * b线程开始执行
* b线程停止执行	  	* b线程停止执行

线程强制执行

void join() 等待该线程终止

//测试join方法 (想象为插队)
public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) 
            System.out.println("线程vip来了"+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 < 100; i++) {
            if (i==50)
                thread.join();//插队
            System.out.println("main"+i);
        }
    }
}

观测线程状态

boolean isAlive() 测试线程是否处于活动状态

public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(()->{
            for (int i = 0; i < 5; 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);//RUN
        //只要线程不终止,就一直输出状态
        while(state!=Thread.State.TERMINATED){
            Thread.sleep(1000);
            state=thread.getState();//更新线程状态
            System.out.println(state);
        }
        //thread.start();//线程死亡后不能再次启动
    }
}

线程优先级

Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行

线程的优先级用数字表示,范围从1~10。主线程和子线程的默认优先级都是5
优先级高只是先执行的概率高,并不一定先执行;
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用

优先级的设定建议在start()调度前

getPriority() 获得当前优先级
setPriority(int pri) 设置线程优先级

Thread.MAX_PRIOROTY=10
Thread.MIN_PRIOROTY=1
Thread.NORM_PRIOROTY=5

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);
        Thread t5=new Thread(myPriority);
        //先设置优先级再启动
        t1.start();
        t2.setPriority(1);
        t2.start();
        t3.setPriority(3);
        t3.start();
        t4.setPriority(10);
        t4.start();
        t5.setPriority(8);
        t5.start();
    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"----》"+Thread.currentThread().getPriority());
    }
}

守护线程

线程分为用户线程和守护线程,虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕,如:后台记录操作日志,监控内存,垃圾回收等。

void setDaemon(boolean on)
守护线程:后台线程,当所有的前台线程全部结束,即使后台线程没执行完,也立刻结束
需在线程启动前设置

//测试守护线程
//上帝守护你
public class TestDaemon {
    public static void main(String[] args) {
        God god=new God();
        You you=new You();
        Thread thread=new Thread(god);
        thread.setDaemon(true);//默认是false,表示是用户线程,普通的线程都是用户线程
        thread.start();//上帝守护线程开启
        new Thread(you).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("开心地活着,第"+i+"天");
        }
        System.out.println("Goodbye,world!");
    }
}

用户线程执行完后,守护线程还运行了一会儿是因为,虚拟机关闭需要一定的时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值