我有以下类:
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
不会强制其他线程执行任务。它只会在有其他线程正在尝试获取 CPU 时间时,强制调用线程让出 CPU 时间给其他线程执行任务。看起来thread1
在完成所有任务之前就已经结束了,或者调度程序选择让thread1
先完成。 - jonhopkins