multiple thread (8)

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值