clock in!
one:internal storage visiblity problems
1.example
a thread is responsible for read data, the other thread is responsible for modify data.
class Counter{
static int count=0;
}
public class Study {
Counter counter=new Counter();
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(()->{
while (Counter.count==0){
正在进行读取操作,while循环一直在发生,所以频繁的进行LOAD 和 CMP操作
}
});
t1.start();
Thread t2=new Thread(()->{
System.out.println("please input an number:");
Scanner scanner=new Scanner(System.in);
Counter.count= scanner.nextInt();
});
t2.start();
}
}
2.occur question 's cause
LOAD:read memory
CMP:compare the value of register whether is zero
question:frequent operation load costs time is so longly
3.solve method
compiler helps us solve this problem-improvement
4.occur question again
but if the other thread modified the value?-unable to terminate the process
result:t2 has modified the value,t1 fail to have the consciousness
solve scheme(ski:m):use volatile(valetl)
other
other
5.other:
register seems to be work memory,internal storage seems to be main memory
other
two: wait 和notify
1.origin:
random a class both can call wait method
2.occur abnormity:
3.excution sequence:
4.observe result
class Study{
public static void main(String[] args) {
Object object=new Object();
Thread t1=new Thread(()->{
synchronized (object){
System.out.println("wait before");//1.
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait after");
}
});
t1.start();
Thread t2=new Thread(()->{
synchronized (object){
System.out.println("notify before");//2
object.notify();
System.out.println("notify after");
}
});
t2.start();
}
}
5.notifyall method