【发布时间】:2017-06-26 08:20:22
【问题描述】:
我是 Java 多线程编程的新手。在这里我想运行两个线程 运行线程 1 wait() notift() 然后线程 2 wait() notify() 同样明智。
有人可以帮我实现下面给出的预期输出
代码
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
synchronized (t){
try {
for(int i = 1; i < = 5; i--) {
System.out.println("Thread: " + threadName + ", " + i);
wait();
notify();
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
预期输出为
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 1
Running Thread-2
Thread: Thread-2, 1
............
Running Thread-1
Thread: Thread-1, 5
Running Thread-2
Thread: Thread-2, 5
当前输出异常是
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 1
Running Thread-2
Thread: Thread-2, 1
Exception in thread "Thread-1" Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at RunnableDemo.run(TestThread.java:16)
at java.lang.Thread.run(Thread.java:745)
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at RunnableDemo.run(TestThread.java:16)
at java.lang.Thread.run(Thread.java:745)
【问题讨论】:
-
阅读 Java 线程 here
-
@KevinAnderson 所以有没有办法达到我的预期结果
-
可能,是的。一旦你学会了如何使用线程,它应该是可能的。
标签: java multithreading