次のコードは、変数を読み書きする一切のロックが存在しない、同期させることができません
import java.sql.Time;
import java.util.concurrent.TimeUnit;
public class SynLock {
public static boolean isstop;
public static void main(String[] args) throws InterruptedException{
System.out.println(isstop);
Thread background = new Thread(()->{
int i=0;
while (!isstop){
i++;
}
});
background.start();
TimeUnit.SECONDS.sleep(1);
isstop=true;
}
}
以下のコードリーダーは、変数をロック
import java.sql.Time;
import java.util.concurrent.TimeUnit;
public class SynLock {
public static boolean isstop;
//写锁
public synchronized static void set(){
isstop=true;
}
//读锁
public synchronized static boolean read(){
return isstop;
}
public static void main(String[] args) throws InterruptedException{
System.out.println(isstop);
Thread background = new Thread(()->{
int i=0;
while (!read()){
i++;
}
});
background.start();
TimeUnit.SECONDS.sleep(1);
set();
}
}
変数名を高めるために揮発性の修飾子も同じ役割を果たすことができます
import java.sql.Time;
import java.util.concurrent.TimeUnit;
public class SynLock {
public static volatile boolean isstop;
public static void main(String[] args) throws InterruptedException{
System.out.println(isstop);
Thread background = new Thread(()->{
int i=0;
while (!isstop){
i++;
}
});
background.start();
TimeUnit.SECONDS.sleep(1);
isstop=true;
}
}