public class thread implements Runnable { Thread a = new Thread(this);
Thread b = new Thread(this); thread() {
a.start();
b.start();
} public static void main(String[] args) {
new thread(); } @Override
public void run() {
int x = 0;
while (x < 5) {
if (Thread.currentThread() == a)
System.out.println("a");
if (Thread.currentThread() == b)
System.out.println("b");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x++;
}
// TODO Auto-generated method stub }}以上程序我想用wait()使得a等待b完成后notify(),怎么改?
有点像操作系统里面的“管程”的概念,做得比较优雅。
可以作为通用的多线程编程模式,移植到C++等语言。
这里只要给这个类增加阻塞对象就可以了
public class thread implements Runnable {
private Object obj=new Object();///用于同步线程
Thread a = new Thread(this);
Thread b = new Thread(this); thread() {
a.start();
b.start();
} public static void main(String[] args) {
new thread(); } @Override
public void run() {
try{
obj.wait();//获得obj的锁
int x = 0;
while (x < 5) {
if (Thread.currentThread() == a)
System.out.println("a");
if (Thread.currentThread() == b)
System.out.println("b");
Thread.sleep(1000);
x++;
}
obj.notify();//释放obj的锁
}catch(Exception e){
e.printStackTrace();
}
}}
private Object obj=new Object();///用于同步线程
Thread a = new Thread(this);
Thread b = new Thread(this); thread() {
a.start();
b.start();
} public static void main(String[] args) {
new thread(); } @Override
public void run() {
try{
obj.wait();//获得obj的锁
int x = 0;
while (x < 5) {
if (Thread.currentThread() == a)
System.out.println("a");
if (Thread.currentThread() == b)
System.out.println("b");
Thread.sleep(1000);
x++;
}
obj.notify();//释放obj的锁
}catch(Exception e){
e.printStackTrace();
}
}}
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at thread.thread.run(thread.java:21)
at java.lang.Thread.run(Unknown Source)
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at thread.thread.run(thread.java:21)
at java.lang.Thread.run(Unknown Source)
Thread b = new Thread(this); thread() {
a.start();
b.start();
} public static void main(String[] args) {
new thread(); } @Override
public void run() {
synchronized (this) { int x = 0;
while (x < 5) {
if (Thread.currentThread() == a)
System.out.println("a");
if (Thread.currentThread() == b)
System.out.println("b");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x++;
}
// TODO Auto-generated method stub }
}}