交替打印奇偶数
问题描述:
-
构造两个线程,交替打印1-100之间的数字,其中线程1打印奇数,线程2打印偶数。
方式1:采用synchronized同步锁和wait,notify线程通信机制来实现。
public class jiaotidayinshuzi {
public static void main(String[] args){
PrintNum p=new PrintNum();
Thread td1=new Thread(p);
Thread td2=new Thread(p);
td1.setName("线程1");
td2.setName("线程2");
td1.start();
td2.start();
}
}
//定义打印函数,通过wait()和notify()交替打印奇偶数
class PrintNum implements Runnable{
int num=1;
@Override
public void run() {
synchronized (this){
while (true){
notify();//唤醒wait()的一个或者所有的线程
if (num<=100){
System.out.println(Thread.currentThread().getName()+":"+num);
num+