美文网首页
java并发控制-无锁和加锁来实现交替打印奇偶数

java并发控制-无锁和加锁来实现交替打印奇偶数

作者: Ace_b90f | 来源:发表于2020-06-11 14:06 被阅读0次

    加锁方式

        static int number = 0;
        static class Ji implements Runnable {
            private String name;
    
            public Ji(String name) {
                this.name = name;
            }
    
            @Override
            public void run() {
                while (number <= 100) {
                    synchronized (WithoutWaitNotify.class) {
                        if ((number % 2) == 1) {
                            System.out.println(number + "  " + name);
                            number++;
                        }
                    }
                }
            }
        }
    
        static class Ou implements Runnable {
            private String name;
    
            public Ou(String name) {
                this.name = name;
            }
    
            @Override
            public void run() {
                while (number <= 100) {
                    synchronized (WithoutWaitNotify.class) {
                        if ((number % 2) == 0) {
                            System.out.println(number + "   " + name);
                            number++;
                        }
                    }
                }
            }
        }
    

    无锁方式

    
        static volatile int count;
    
        public static void main(String[] args) {
            new Thread(new Ji()).start();
            new Thread(new Ou()).start();
        }
    
        static class Ji implements Runnable {
    
            int ccount = 1;
    
            @Override
            public void run() {
                while (true) {
                    if (count > 1000)
                        break;
                    if (count == ccount) {
                        System.out.println("Ji: " + count);
                        ccount = count + 2;
                        count++;
                    }
                }
            }
        }
    
        static class Ou implements Runnable {
            int ccount = 0;
    
            @Override
            public void run() {
                while (true) {
                    if (count > 1000) {
                        break;
                    }
                    if (count == ccount) {
                        System.out.println("Ou: " + count);
                        ccount = count + 2;
                        count++;
                    }
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:java并发控制-无锁和加锁来实现交替打印奇偶数

          本文链接:https://www.haomeiwen.com/subject/tdlbtktx.html