概述
yield()
yield()的作用是让步。它能让当前线程由“运行状态”进入到“就绪状态”,从而让其它具有相同优先级的等待线程获取执行权;但是,并不能保证在当前线程调用yield()之后,其它具有相同优先级的线程就一定能获得执行权;也有可能是当前线程又进入到“运行状态”继续运行!
curentThread()方法的定义:
curentThread() 方法可返回代码段正在被哪个线程调用的信息,若用户未进行命名则系统会自动生成一个命名。
class TH1 extends Thread{
TH1(){
super.setName ("让步线程");
}
@Override
public void run() {
while (true){
Thread.yield ();//当前线程让步,执行的少
System.out.println (this.getName());
}
}
}
class TH2 implements Runnable{
@Override
public void run() {
while (true){
System.out.println (Thread.currentThread ().getName ());//Thread.currentThread ()获得当前线程的引用。
}
}
}
public class takeoff {
public static void main(String[] args) {
TH1 t = new TH1 ();
t.start ();
TH2 th = new TH2 ();
Thread t1 = new Thread (th);
t1.start ();
}
}
执行结果(片段):
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
让步线程
最后
以上就是忧虑母鸡为你收集整理的Java线程||线程让步yield()及curentThread()方法的作用的全部内容,希望文章能够帮你解决Java线程||线程让步yield()及curentThread()方法的作用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复