• 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1


    Java代码  
    package com.yx.zzg;
    
    public class ThreadTest1 {
    
        private int j;
    
        public static void main(String args[]) {
    
            ThreadTest1 tt = new ThreadTest1();
    
            Inc inc = tt.new Inc();
    
            Dec dec = tt.new Dec();
    
            for (int i = 0; i < 2; i++) {
                Thread t = new Thread(inc);
                t.start();
                t = new Thread(dec);
                t.start();
            }
    
        }
    
        private synchronized void inc() {
            j++;
            System.out.println(Thread.currentThread().getName() + "-inc:" + j);
        }
    
        private synchronized void dec() {
            j--;
            System.out.println(Thread.currentThread().getName() + "-dec:" + j);
        }
    
        class Inc implements Runnable {
    
            public void run() {
                for (int i = 0; i < 100; i++) {
                    inc();
                }
            }
        }
    
        class Dec implements Runnable {
    
            public void run() {
                for (int i = 0; i < 100; i++) {
                    dec();
                }
            }
        }
    
    }


    注:这里inc方法和dec方法加synchronized关键字是因为当两个线程同时操作同一个变量时,就算是简单的j++操作时,在系统底层也是通过多条机器语句来实现,所以在执行j++过程也是要耗费时间,这时就有可能在执行j++的时候,另外一个线程H就会对j进行操作,因此另外一个线程H可能操作的可能就不是最新的值了。因此要提供线程同步。

    版本2:

    本版本不需要synchronized,而用AtomicInteger代替

    package com.yx.zzg;
    
    public class ThreadTest1 {
    
       private AtomicInteger j=new AtomicInteger();public static void main(String args[]) {
    
            ThreadTest1 tt = new ThreadTest1();
    
            Inc inc = tt.new Inc();
    
            Dec dec = tt.new Dec();
    
            for (int i = 0; i < 2; i++) {
                Thread t = new Thread(inc);
                t.start();
                t = new Thread(dec);
                t.start();
            }
    
        }
    
        private synchronized void inc() {
            j.incrementAndGet();
            System.out.println(Thread.currentThread().getName() + "-inc:" + j);
        }
    
        private synchronized void dec() {
            j.decrementAndGet();
            System.out.println(Thread.currentThread().getName() + "-dec:" + j);
        }
    
        class Inc implements Runnable {
    
            public void run() {
                for (int i = 0; i < 100; i++) {
                    inc();
                }
            }
        }
    
        class Dec implements Runnable {
    
            public void run() {
                for (int i = 0; i < 100; i++) {
                    dec();
                }
            }
        }
    
    }
  • 相关阅读:
    rgbdslam 源代码的实现
    键值对排序并MD5加密
    字符编码
    排序算法
    Bridge Pattern (桥接模式)
    Visitor Pattern 和 doubledispatch
    栈、队列、链表
    如何使用visio
    架构师论文
    英语写作句子
  • 原文地址:https://www.cnblogs.com/langtianya/p/4628611.html
Copyright © 2020-2023  润新知