带你一次搞明白Java多线程,线程的常用方法--2

64 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

5、getId()

thread.getId()可以获得线程的唯一标识

注意:

某个编号的线程运行结束后,该编号可能被后续创建的线程使

重启的 JVM 后,同一个线程的编号可能不一样


package com.wkcto.threadmehtod.p4getid;

/**

* Author : 老崔

*/

public class SubThread5 extends Thread {

@Override

public void run() {

System.out.println("thread name = " + Thread.currentThread().getName()

+ ", id == " + this.getId() );

}

}
package com.wkcto.threadmehtod.p4getid;

/**

* Author : 老崔

*/

public class Test {

public static void main(String[] args) {

System.out.println( Thread.currentThread().getName() + " , id = " +
Thread.currentThread().getId());

//子线程的 id

for(int i = 1; i <= 100; i++){

new SubThread5().start();

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

6、yield()

Thread.yield()方法的作用是放弃当前的 CPU 资源,

package com.wkcto.threadmehtod.p5yield;

/**

* 线程让步

* Author : 蛙课网老崔

*/

public class SubThread6 extends Thread {

@Override

public void run() {

ong begin = System.currentTimeMillis();

long sum = 0;

for(int i = 1; i <= 1000000; i++){

sum += i;

Thread.yield();

//线程让步, 放弃 CPU 执行权

}

long end = System.currentTimeMillis();

System.out.println("用时: " + (end - begin));

}

}
package com.wkcto.threadmehtod.p5yield;

/**

* Author : 老崔

*/

public class Test {

public static void main(String[] args) {

//开启子线程,计算累加和

SubThread6 t6 = new SubThread6();

t6.start();

//在 main 线程中计算累加和

long begin = System.currentTimeMillis();

long sum = 0;

for(int i = 1; i <= 1000000; i++){

sum += i;

}

long end = System.currentTimeMillis();

System.out.println("main 方法 , 用时: " + (end - begin));

}

}

7、setPriority()

thread.setPriority( num ); 设置线程的优先级

java 线程的优先级取值范围是 1 ~ 10 , 如果超出这个范围会抛出异常 IllegalArgumentException.

在操作系统中,优先级较高的线程获得 CPU 的资源越多

线程优先级本质上是只是给线程调度器一个提示信息,以便于调度器决定先调度哪些线程. 注意不能保证优先级高的线程先运行.

Java 优先级设置不当或者滥用可能会导致某些线程永远无法得到运行,即产生了线程饥饿.

线程的优先级并不是设置的越高越好,一般情况下使用普通的优先级即可,即在开发时不必设置线程的优先级

线程的优先级具有继承性, 在 A 线程中创建了 B 线程,则 B 线程的优先级与 A 线程是一样的.


/**

* Author : 老崔

*/

public class ThreadA extends Thread {

@Override

public void run() {

long begin = System.currentTimeMillis();

long sum = 0 ;

for(long i = 0 ; i<= 10000000000L; i++){

sum += i;

}

long end = System.currentTimeMillis();

System.out.println("thread a : " + (end - begin));

}

}
package com.wkcto.threadmehtod.p6priority;

/**

* Author : 老崔

*/

public class Test {

public static void main(String[] args) {

ThreadA threadA = new ThreadA();

threadA.setPriority(1);

threadA.start();

ThreadB threadB = new ThreadB();

threadB.setPriority(10);

threadB.start();

}

}

****