加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java中使用Thread.yield()

发布时间:2020-12-15 04:08:47 所属栏目:Java 来源:网络整理
导读:我有以下课程: package net.adjava.multithreading;public class MyResource { private int a; public int getA() { return a; } public void setA(int a) { this.a = a; }} package net.adjava.multithreading;public class Thread1 extends Thread { MyRe
我有以下课程:

package net.adjava.multithreading;

public class MyResource {

    private int a;



    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

}
package net.adjava.multithreading;

public class Thread1 extends Thread {
    MyResource m;

    public Thread1(MyResource m) {
        super();
        this.m = m;
    }

    @Override
    public void run() {
        System.out.println("Current Thread name1 :"
                + Thread.currentThread().getName());

        for (int i = 0; i < 10000; i++) {
            m.setA(i);
            System.out.println("Set method sets the value of a as: " + i);
            System.out.println("Current Thread name1 :"
                    + Thread.currentThread().getName());

            Thread.yield();

        }
    }
}
package net.adjava.multithreading;

public class Thread2 extends Thread {

    MyResource m;
    public Thread2(MyResource m) {
        super();
        this.m = m;
    }
    @Override
    public void run() {
        System.out.println("Current Thread name2 :" + Thread.currentThread().getName());

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

            System.out.println(" value of a as per getter method is :"
                    + m.getA());
            System.out.println("Current Thread name2 :" + Thread.currentThread().getName());


        }
        System.out.println("waiting for thread to end");

    }

}
package net.adjava.multithreading;

public class ThreadExecutionPoint {

    public static void main(String args[])
    {
        System.out.println("Current Thread name main :" + Thread.currentThread().getName());

        MyResource m = new MyResource();
        Thread1 th1 = new Thread1(m);
        Thread2 th2 = new Thread2(m);
        th1.start();
        th2.start();

    }
}

我试图用上面的类来理解yield()的目的.在尝试这个例子之前我所知道的yield()就是它暂停调用它的线程.所以为了测试它我在Thread1类中使用了yield方法.所以基本上根据我的理解,thread1应该执行for循环一次然后应该暂停并等待其他线程完成.但输出显示不同的结果.输出显示第一个thread1被执行然后执行thread2.有人可以纠正我错过的东西吗?或者我对yield()的理解有问题.

解决方法

文档说明这与yield方法有关:

Causes the currently executing thread object to temporarily pause and allow other threads to execute.

即使可能发生这种情况,也没有任何东西可以保证您选择要处理的线程不是同一个.

由于几乎所有的协作线程都不依赖于此,因为您无法保证预期的功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读