我有以下类(class):
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.
即使认为可能会发生这种情况,也无法保证将被选择进行处理的线程不是同一线程。
由于几乎所有协调线程,请不要依赖它,因为无法保证您期望的功能。
关于java - 在 Java 中使用 Thread.yield(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15668023/