私は次のクラスを持っています:
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 メソッドを使用しました。したがって、基本的に私の理解によれば、スレッド1はforループを1回実行してから、一時停止して他のスレッドが完了するのを待つ必要があります。しかし、出力は異なる結果を示しています。出力は、最初にスレッド 1 が実行され、次にスレッド 2 が実行されることを示しています。誰かが私が欠けているものを修正してもらえますか? または、yield() に関する私の理解に何か問題があります。