package practice5;
/**
* 5、制作两个线程对象,要求用同步块的方式使第一个线程运行2次,
* 然后将自己阻塞起来,唤醒第二个线程,第二个线程再运行2次,
* 然后将自己阻塞起来,唤醒第一个线程 ,两 个线程交替执行。
* @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();
}
}
}
}
}