50,523
社区成员
发帖
与我相关
我的任务
分享
public class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Total is: " + b.total);
}
}
class ThreadB extends Thread {
int total;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
total += i;
}
}
}
class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
}
}
public class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
ThreadB b2 = new ThreadB();
b2.start();
b.start();
synchronized (b2) {
try {
System.out.println("Waiting for b2 to complete...");
//b2.wait();
b.join();
System.out.println("b Total is: " + b.total);
b2.wait(1000);
System.out.println("b2 Total is: " + b2.total);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class ThreadB extends Thread {
int total;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
total += i;
}
}
}
wait()方法是可以有参数的,延迟多少毫秒。join()方法就是让该进程先运行