多线程学习,线程创建及常用方法及优先级

package com.senior.test;

/**
 * 测试Thread类中的常用方法
 * 1、start():启动当前线程:调用当前线程的run()
 * 2、run():通常需要重写Thread类中的方法,将创建的线程要执行的操作声明在此方法中
 * 3、currentThread:静态方法,返回当前代码执行的线程
 * 4、getName():获取当前线程的名字
 * 5、setName():设置当前线程的名字
 * 6、yield() : 释放当前CPU的执行权
 * 7、join():在线程A中调用线程B的方法join(),
 * 此线程A就进入阻塞状态,直到线程B执行完以后,A才结束堵塞状态
 * 8、sleep(Long millitime) : 睡眠,让当前线程睡眠,在指定的毫秒中,
 * 当前线程为堵塞状态
 * 9、isAlive():判断当前线程是否存活
 *
 *
 * 线程的优先级:
 * 1、
 * NORM_PRIORITY = 5; 默认优先级
 * MAX_PRIORITY = 10
 * MIN_PRIORITY = 1
 *
 * 2、
 * 如何获取和设置当前线程的优先级
 * getPriority():获取线程的优先级
 * setPriority(int p):设置线程的优先级
 *
 * 说明:高优先级在线程要抢占低优先级cpu的执行权,但是从概率上来讲,
 * 高优先级高概率被优先执行,并不意味着当高优先级的线程执行之后低优先级的才执行
 *
 */
public class ThreadMethodTest {
    public static void main(String[] args) {
        MyThread3 myThread3 = new MyThread3("Thread : 1");
        myThread3.setPriority(Thread.MAX_PRIORITY);
        myThread3.start();

        Thread.currentThread().setName("主线程");
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        //给主线程命名
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
            }

            if (i == 20) {
                try {
                    myThread3.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println(myThread3.isAlive());
    }
}

class MyThread3 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                /*try {
                    sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
            }

            /*if (i % 20 == 0) {
                //释放当前的执行权,切换到下一个线程
                yield();
            }*/
        }
    }
    public MyThread3(String name) {
        super(name);
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值