简体   繁体   中英

Thread won't release lock after wait()

Sorry if there are other similar questions but I couldn't find any, I am a beginner to concurrent programming and this problem has been bugging me for awhile, which I really need to understand what is the mistake I have made, or else I couldn't proceed into my assignment.

What I am trying to achieve is to print "1" from 'Test' that is handled by a thread and print "from Test 2" from 'Test 2' which is also handled by a thread, but only "1" is printed. What should I do?

================================

import java.util.logging.Level;
import java.util.logging.Logger;

public class Test implements Runnable {

    Third third;

    public Test(Third third){
        this.third = third;
    }

    public void run() {
        while (true) {
            synchronized (third) {
                try {
                    System.out.println("1");
                    third.wait();
                } catch (InterruptedException ex) {

                }

            }
        }
    }
}

=====================


public class Test2 implements Runnable{
    Test test;
    Third third;

    public Test2(Test test, Third third){
        this.test = test;
        this.third = third;
    }

    public void run(){
        while(true){
            synchronized(third){
                third.notifyAll();
                System.out.println("from test 2");
            }
        }
    }
}

================================

public class Third {

}

==============================

public class main {
    public static void main(String[] args) throws InterruptedException{

        Third third = new Third();
        Test test = new Test(third);
        Test2 test2 = new Test2(test, third);

        Thread t1 = new Thread(test);
        Thread t2= new Thread(test2);

        t1.run();
        t2.run();
        t2.join();
        t1.join();
    }
}

The output

You should not call run method directly as it will not create any thread.It invokes like a normal method. Instead of run() method, you should call start() method.

One more thing, what you're doing with shared resource Third. There could be synchronize method which is accessible by different thread.

Class name should be start with Capital letter and should follow CamelCase.

public class main { public static void main(String[] args) throws InterruptedException{

    Third third = new Third();
    Test test = new Test(third);
    Test2 test2 = new Test2(test, third);

    Thread t1 = new Thread(test);
    Thread t2= new Thread(test2);

    t1.start();
    t2.start();
    t2.join();
    t1.join();
}

}

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