62,616
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.TimeUnit;
public class Demo8 {
public static void main(String[] args) {
B b = new B();
A a = new A(b);
b.start();
a.start();
}
}
class A extends Thread {
private B b;
public A(B b) {
this.b = b;
}
@Override
public void run() {
try {
int i = 0;
while (true) {
i++;
System.out.println("A is runing");
TimeUnit.MILLISECONDS.sleep(500);
if (i > 5) {
System.out.println("A 开始沉睡3秒");
b.join(3000);
System.out.println("A 醒来正常执行");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class B extends Thread {
@Override
public void run() {
try {
while (true) {
System.out.println("B is runing");
TimeUnit.MILLISECONDS.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public A extends Thread{
public void run(){
}
}
public B extends Thread{
private boolean pause;
public B(){
super();
this.pause = false;
}
public synchronized void pause(){
this.pause = true;
}
public void run(){
while(true){
synchronized(this){
if(pause){
sleep(3000L);
}
}
// do something
}
}
}