Java作业代做 The example code is given as:

The example code is given as:

Java作业代做 The volatile decorates the variable counter. The removal of the decorator will cause all threads reading the variable's value at the

 
public class RaceCondition { Java作业代做
    public volatile int counter = 0;
 
    public int get(){
//        The thread will wait 0.1 second, +1 the counter, then read it out.
        try{
            Thread.sleep(100);
        } catch (InterruptedException e){
            e.printStackTrace();
        }
        counter ++;
        return counter;
    }
 
    public static void main(String[] args){
        // 10 threads trying to play with the counter value.
        RaceCondition rc = new RaceCondition();
       for(int i = 0; i < 10; i++){ Java作业代做
            new Thread(new Runnable(){
                @Override
                public void run(){
//                    rc.incrementCounter();
                    System.out.println("Thread " + Thread.currentThread().getName() + " gets " + rc.get());
                }
            }).start();
        }
    }
}

 

In the sample, 10 threads will start and plus 1 to the counter variable. Then print it out. The race condition may be seemed as that the printed value repeated because the threads access it at the same time.  Java作业代做

The volatile decorates the variable counter. The removal of the decorator will cause all threads reading the variable's value at the same time, and causing a race condition. With the decorator, the writing operation will always be completed before reading, so the printed value will not repeat.

Java作业代做更多代写: HomeWork cs作业     金融代考    postgreSQL代写         IT assignment代写     统计代写  算法algorithm作业代写

发表回复

客服一号:点击这里给我发消息
客服二号:点击这里给我发消息
微信客服1:essay-kathrine
微信客服2:essay-gloria