//线程1 public void run() { while(i++ < 100) { //do you business here } notify(); } //线程2 public void run() { while(i < 100)wait(); //do you business here } 两个线程共用一个i
public class TestApp { public static void main(String[] args) { ThreadB b = new ThreadB(); b.start(); synchronized (b) { try { b.wait(); //等待线程B int total = b.i; System.out.println("当I不等于100时,"); for (total = 100; total > 0; total--) { System.out.println("i =" + total + " "); } } catch (InterruptedException e) { } } } } class ThreadB extends Thread { int i = 0; public void run() { synchronized (this) { for (int j = 0; j < 100; j++) { i++; System.out.println("i =" + i + " "); if (i == 100) { notify();//唤醒线程 } } } } } 主要是理解notify()和wait()方法,这两个方法是属于最底层的Object基础类的,也就是说不只是Thread对象,而是每个对象都有notify()和wait()方法。
public void run()
{
while(i++ < 100)
{
//do you business here
}
notify();
}
//线程2
public void run()
{
while(i < 100)wait();
//do you business here
}
两个线程共用一个i
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
try {
b.wait(); //等待线程B
int total = b.i;
System.out.println("当I不等于100时,");
for (total = 100; total > 0; total--) {
System.out.println("i =" + total + " ");
} } catch (InterruptedException e) {
}
}
}
}
class ThreadB extends Thread {
int i = 0;
public void run() {
synchronized (this) {
for (int j = 0; j < 100; j++) {
i++;
System.out.println("i =" + i + " ");
if (i == 100) {
notify();//唤醒线程
}
}
}
}
}
主要是理解notify()和wait()方法,这两个方法是属于最底层的Object基础类的,也就是说不只是Thread对象,而是每个对象都有notify()和wait()方法。
to:dyflovexlp兄,你的意思是写两个thread类吗?如果是的话怎么调用,请指点。to:jiajiadounai兄,代码里有哪两个线程,b和main吗? 还有一点不明白,我把“b.wait(); ”去掉,它为什么会先打印“ System.out.println("当I不等于100时,");”这一句,就是说为什么会先执行主线程,而不先执行ThreadB.run()呢,主面不是有 b.start();语句吗?