1、sleep(long millis): 指定线程睡眠毫秒数。sleep是静态方法,哪个线程执行sleep方法那么就是哪个线程睡眠

2、currentThread(): 返回当前的线程对象,currentThread是静态方法,哪个线程执行了currentThread()代码就返回那个线程的对象

代码:

public class CustomThread extends Thread {
public static void main(String[] args) {
//创建线程对象
CustomThread customThread = new CustomThread("customThread");
//启动线程
customThread.start();
//currentThread(): 返回当前的线程对象
System.out.println("main线程:" + Thread.currentThread()); //main线程:Thread[main,5,main]
}

@Override
public void run() {
System.out.println("this:" + this); //this:Thread[customThread,5,main]
System.out.println("CustomThread:" + Thread.currentThread()); //CustomThread:Thread[customThread,5,main]
}

public CustomThread(String name) {
super(name);
}

}

截图:

(JAVA)线程之sleep、currentThread、getPrority、setPrority方法

3、getPrority() : 返回当前线程对象的优先级,默认线程的优先级为5

public class CustomThread extends Thread {
public static void main(String[] args) {

              //创建线程对象
              CustomThread customThread = new CustomThread();
              //getPrority(): 返回当前线程对象的优先级,默认线程的优先级为5
              System.out.println("自定义线程的优先级:" + customThread.getPriority());              //自定义线程的优先级:5

              System.out.println("主线程的优先级为:" + Thread.currentThread().getPriority());   //主线程的优先级为:5

      }

}

(JAVA)线程之sleep、currentThread、getPrority、setPrority方法

4、setPrority(int newPriority): 设置线程的优先级

代码:

public class CustomThread extends Thread {
public static void main(String[] args) {
//创建线程对象
CustomThread customThread = new CustomThread();
//优先级的范围是[1,10],优先级的数字越大,优先级越高
customThread.setPriority(10);
//开启线程
customThread.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}

@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}

}

截图:

(JAVA)线程之sleep、currentThread、getPrority、setPrority方法

相关文章:

  • 2021-10-18
  • 2021-05-30
  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
  • 2021-11-17
  • 2021-08-09
  • 2021-07-19
猜你喜欢
  • 2021-11-23
  • 2022-12-23
  • 2021-08-03
  • 2021-12-19
  • 2021-12-24
  • 2022-12-23
相关资源
相似解决方案