两个线程交替打印100次AB

 Runnable接口代码:

public class AbThread implements  Runnable {

     char[] content={'B','A'};
     int count =1;

    @Override
    public void run() {
        synchronized (this){
        try {
            while(count<=100) {
                System.out.println(Thread.currentThread().getName() +"  次数 "+count+ content[count % 2]);
                ++count;
                notify();
                if (count <=100) {
                    wait();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    }
}

用线程池进行测试:

  ExecutorService  executorService= Executors.newCachedThreadPool();
  Runnable  runnable=new AbThread();
  executorService.execute(runnable);
  executorService.execute(runnable);

测试结果:

2.3个线程交替打印abc


public class AbThread implements  Runnable {
        Object a;
        Object b;
        String name;
        int  count=1;
        AbThread(String name,Object a,Object b ){
            this.name=name;
            this.a=a;
            this.b=b;
        }
        
    @Override
    public void run() {
        while(count<=10) {
            try {
                synchronized (a) {
                    synchronized (b) {
                        System.out.println(Thread.currentThread().getName() + "  次数 " + count + name);
                        ++count;
                        b.notifyAll();
                    }
                    a.notifyAll();
                    if (count <= 10) {
                        a.wait();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

测试代码:

              Object a=new Object();
              Object b=new Object();
              Object c=new Object();
              ExecutorService  executorService= Executors.newCachedThreadPool();
              executorService.execute(new AbThread("A",b,c));
              Thread.sleep(1000);
              executorService.execute(new AbThread("B",c,a));
              Thread.sleep(1000);
              executorService.execute(new AbThread("C",a,b));
发布了68 篇原创文章 · 获赞 93 · 访问量 8523

猜你喜欢

转载自blog.csdn.net/qq_34707456/article/details/103027820