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);
}
}