wait() 后线程不会释放锁

Thread won't release lock after wait()

对不起,如果还有其他类似的问题,但我找不到任何问题,我是并发编程的初学者,这个问题困扰了我一段时间,我真的需要了解我犯了什么错误,否则我无法继续我的任务。

我想要实现的是从线程处理的 'Test' 打印“1”,并从同样由线程处理的 'Test 2' 打印 "from Test 2",但只打印“1”。我该怎么办?

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

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

您不应直接调用 运行 方法,因为它不会像普通方法那样创建任何 thread.It 调用。您应该调用 start() 方法,而不是 运行() 方法。

还有一件事,你在用共享资源做什么第三。可能有不同线程可以访问的同步方法。

Class 名称应以大写字母开头并遵循驼峰式命名法。

publicclass主要{ 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();
}

}