Bug*_*der 4 java multithreading mutex
据我所知,我想在互斥锁上调用wait(),当我希望当前线程停止工作,直到另一个线程在同一个互斥对象上调用notify().这似乎不起作用.
我正在尝试打印线程1-10.然后等待另一个线程打印11-20.然后第一个线程将再次打印21-30
Main.java
public class Main {
public static void main(String[] args) throws InterruptedException {
Object mutex = 1;
Thread child1 = new Thread(new Child1(mutex));
Thread child2 = new Thread(new Child2(mutex));
child1.start();
child2.start();
}
}
Run Code Online (Sandbox Code Playgroud)
Child1.java
public class Child1 implements Runnable {
Object mutex;
public Child1(Object mutex){
this.mutex = mutex;
}
public void run() {
synchronized (mutex) {
for(int c = 0; c < 10; c++){
System.out.println(c+1);
}
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int c = 20; c < 31; c++){
System.out.println(c+1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Child2.java
public class Child2 implements Runnable {
Object mutex;
public Child2(Object mutex) {
this.mutex = mutex;
}
public void run() {
synchronized (mutex) {
for (int c = 11; c < 21; c++) {
System.out.println(c);
}
notify();
}
}
}
Run Code Online (Sandbox Code Playgroud)
产量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Exception in thread "Thread-0"
18
19
20
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at task42.Child1.run(Child1.java:18)
at java.lang.Thread.run(Thread.java:745)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at task42.Child2.run(Child2.java:15)
at java.lang.Thread.run(Thread.java:745)
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
您必须添加mutex对wait()和的引用notify(); 也就是说,更改wait()到mutex.wait()和notify()到mutex.notify().
没有这个,你正在呼叫等待/通知this(method()相当于this.method())
以下是您的代码,并进行了相应的更改:
Child1.java
public class Child1 implements Runnable {
Object mutex;
public Child1(Object mutex){
this.mutex = mutex;
}
public void run() {
synchronized (mutex) {
for(int c = 0; c < 10; c++){
System.out.println(c+1);
}
try {
mutex.wait(); // Changed here
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int c = 20; c < 31; c++){
System.out.println(c+1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Child2.java
public class Child2 implements Runnable {
Object mutex;
public Child2(Object mutex) {
this.mutex = mutex;
}
public void run() {
synchronized (mutex) {
for (int c = 11; c < 21; c++) {
System.out.println(c);
}
mutex.notify(); // Changed here
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2545 次 |
| 最近记录: |