java - wait() 后线程不会释放锁
问题描述
抱歉,如果还有其他类似的问题,但我找不到任何问题,我是并发编程的初学者,这个问题一直困扰着我一段时间,我真的需要了解我犯了什么错误,否则我不能不要继续我的任务。
我想要实现的是从由线程处理的“测试”中打印“1”,并从同样由线程处理的“测试 2”中打印“来自测试 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();
}
}
解决方案
您不应该直接调用 run 方法,因为它不会创建任何线程。它像普通方法一样调用。您应该调用 start() 方法,而不是 run() 方法。
还有一件事,您对共享资源所做的事情 第三。可能有不同线程可以访问的同步方法。
类名应以大写字母开头,并应遵循 CamelCase。
公共类主{公共静态无效主(字符串[]参数)抛出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();
}
}
推荐阅读
- reactjs - 如何解决这个异常 Unexpected token < in JSON at position 0?
- java - 如何在java中接收广播消息
- javascript - Javascript 像幻灯片一样改变 DIV
- html - 为什么在课堂内选择课程不起作用
- php - 为什么 laravel \Storage::store 方法会导致此错误?
- google-sheets - 基于输入单元格数量的动态公式
- php - 为什么 $_POST 数组总是空的,即使 URL 有查询字符串参数?
- php - 使用 LiipFunctionalTestBundle 在 setUpBeforeClass 中加载数据夹具
- ethereum - web3.eth.getAccounts 不适用于 infura
- ros - 在现有项目中切换 ROS 本地规划器