Initializing two threads with the same instance of a runnable

前端 未结 4 1805
眼角桃花
眼角桃花 2020-11-29 05:39

Is it bad programming to initialize two threads with the same instance of a runnable? What difference would it make to initialize with separate instances of a runnable, and

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 06:04

    To make understand easily(based on the comment of Stephen), added the below program block about the impact of accessing the instance variable from a non-synchronized block with the same instance of Runnable displays the unexpected results.

    public class SynchronizedInstanceMethod implements Runnable{
    
    private int counter;
    
    public SynchronizedInstanceMethod(int counterValue){
        this.counter = counterValue;
    }
    
    private synchronized void displayMessage(){
        System.out.println(" Display Message ");
    }
    
    private void modifyCounter(){
        this.counter++;
        System.out.println("Value -- "+ this.counter);
    }
    
    @Override
    public void run() {
        this.displayMessage();
        this.modifyCounter();
    }
    
    public static void main(String[] args) {
        SynchronizedInstanceMethod instance = new SynchronizedInstanceMethod(5);
        new Thread(instance).start();
        new Thread(instance).start();
    }
    }
    

提交回复
热议问题