/題目要求:
//有一個對象,對象中有一個status字段,字段類型是int,status的初始值爲0。
//有兩個線程,一個線程將這個對象的status字段更新爲1,另一個線程將這個對象的status字段更新爲2。
//要求這個對象的status字段的值被這兩個線程交替更新,即121212,或者212121,均可。
//要求每個線程更新status字段10次,請考慮使用線程同步的方式來實現,避免死鎖。
public class Test2 {
private static Object lock = new Object();
private static int status = 0;
static boolean flag = true;
public static void main(String[] args) {
Thread t1 = new Thread( () -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
lock.notify();
flag = false;
if(!flag){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
status = 1;
System.out.println(String.format("loop:%d,status:%s", i, status));
}
}
});
Thread t2 = new Thread(() ->{
for (int i = 0; i < 11; i++) {
synchronized (lock) {
lock.notify();
flag = true;
if (flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
status = 2;
System.out.println(String.format("loop:%d,status:%s", i, status));
}
}
});
t2.start();
t1.start();
}
}