多线程|java多线程实现奇偶数输出

两种实现方式1:普通synchronized版实现、 2:使用Semaphore版实现
一:普通synchronized版实现

在这里插入代码片public class Ceshi999 { static int result = 0; public static void main(String[] args){ Thread thread = new Thread(new Jiou(0)); thread.start(); Thread thread1 = new Thread(new Jiou(1)); thread1.start(); } static class Jiou implements Runnable{ private int i; public Jiou(int i){ this.i = i; } @Override public void run() { while (result<100){ synchronized (Jiou.class){ System.out.println("thread"+i+":"+result++); Jiou.class.notify(); try { Jiou.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }

【多线程|java多线程实现奇偶数输出】二:使用Semaphore版实现
public class Ceshi888 { staticint result = 0; public static void main(String[] args) throws InterruptedException { int N = 3; Thread threads[] = new Thread[N]; //声明N个数据 Semaphore semaphore[] = new Semaphore[N]; //声明N个信息号量 for(int i=0; i100){ System.exit(0); } }catch (Exception e){ e.printStackTrace(); }finally { currentSemphore.release(); } } } }); threads[i].start(); } } }

    推荐阅读