很抱歉,如果还有其他类似问题,但我找不到,我是兼容编程的初学者,这个问题一直困扰着我,我真的需要了解我犯的错误是什么,否则我无法进入我的任务。
我想要实现的是打印" 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();
}
}
答案 0 :(得分:0)
你不应该直接调用run方法,因为它不会创建任何线程。它像普通方法一样调用。而不是run()方法,你应该调用start()方法。
还有一件事,你正在使用共享资源做什么。可以有不同线程可以访问的同步方法。
班级名称应以大写字母开头,并应遵循CamelCase。
public class main { public static void main(String [] args)抛出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();
}
}