package practice5;
/**
* 5、制作兩個線程對象,要求用同步塊的方式使第一個線程運行2次,
* 然后將自己阻塞起來,喚醒第二個線程,第二個線程再運行2次,
* 然后將自己阻塞起來,喚醒第一個線程 ,兩 個線程交替執(zhí)行。
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
ThreadA t = new ThreadA();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.setName("線程一");
t2.setName("線程二");
t1.start();
t2.start();
}
}
class ThreadA implements Runnable {
int num = 1;
public void run() {
while (true) {
synchronized (this) {
notify();
if (num >0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "\t運行第一次 " );
num++;
} else {
break;
}
if (num > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "\t運行第二次" );
num++;
} else {
break;
}
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}