简体   繁体   中英

writing synchronized method java

I can not understand why no thread never enters into the method wait

public class File {

    private boolean writing = false;

    public synchronized void write()
    { 
        String name = Thread.currentThread().getName();
        while(this.writing == true){
            System.out.println(name +" wait "); 
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.writing=true;
        System.out.println(name +" writing ");
        try{
            Thread.sleep((int)(Math.random()*3000));
        } catch( InterruptedException e){
            e.printStackTrace();
        }
        this.writing=false;
        System.out.println(name +" writing end ");
        this.notifyAll();
    }   
}

public class M_thread extends Thread{
    File file;

    public M_thread(String name,File f){
        super(name);
        this.file=f;
    }

    public void run(){
        while(true){
            file.write();
        }
    }   
}


public class Main {

    public static void main(String[] args) {
        File file=new File();
        new M_thread("t1",file).start();
        new M_thread("t2",file).start();
        new M_thread("t3",file).start();    
    }
}

In my code as I can prevent the problem of starvation caused by the simulation method of writing with sleep ? Because if a thread is put to sleep for a long time always will never write than one that you put to sleep for a short time

I can not understand why no thread never enters into the method wait Well, this is relatively easy to describe:

public synchronized void write() {
    // ...
}

This is the same as:

public void write() {
    synchronized(this) {
        // ...
    }
}

That means, that only one thread with the lock this can enter this block. Since you're using the same instance of File :

File file=new File();
new M_thread("t1",file).start();
new M_thread("t2",file).start();
new M_thread("t3",file).start(); 

.. every Thread has the same object reference on this . Therefore, if one thread enters the method write , then the other thread have to wait until this one thread releases the lock on this . And since the default value of writing is false (and the value will be reset to false if a thread leaves the write method), the loop while(this.writing == true) will never be entered.

Your understanding of synchronization is a bit off, it is simpler than you think.

None of your threads will be in write() at the same time because it is synchronized . So, none of the extraneous wait/notify logic you have is necessary. this.writing will never be true at the start of write() because you set it to false just before leaving every write() , and since write() is synchronized , no threads are "jumping in" to the middle of it anyways. That is, no thread will ever execute write() during that period that this.writing is true.

You can get rid of all of that logic. This is sufficient, as synchronized already does this work for you:

public synchronized void write()
{ 
    String name = Thread.currentThread().getName();
    System.out.println(name +" writing ");
    Thread.sleep((int)(Math.random()*3000)); 
    System.out.println(name +" writing end ");
}

Just declaring write() as synchronized will already cause other threads that call write() to wait their turn.

Note that your sleep() call will not throw InterruptedException in your example, as you never call interrupt() ( interruptions do not come out of nowhere ). I have left out that exception handler for simplicity. That said, if you are constructing code to be used in other situations, it's never a bad idea to make it interrupt() -safe, since you never know how your code will end up being used in the future (somebody may use it in a context where they expect interrupt() to work).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM