线程学习之面试题


设计4个线程, 2个线程每次对j加1,2个线程每次对j减1,写出程序。


package com.lyj.practice;

public class MultiThreadShareDate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        // 2个线程对j加1
        for (int i = 0; i < 2; i++) {
            new Thread(new IncrementRun(shareData)).start();
        }

        // 2个线程对j减1
        for (int i = 0; i < 2; i++) {
            new Thread(new DecrementRun(shareData)).start();
        }
    }
}

class IncrementRun implements Runnable {
    private ShareData shareData;

    public IncrementRun(ShareData shareData) {
        this.shareData = shareData;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            shareData.increment();
        }
    }

}

class DecrementRun implements Runnable {
    private ShareData shareData;

    public DecrementRun(ShareData shareData) {
        this.shareData = shareData;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            shareData.decrement();
        }
    }

}

//封装操作
class ShareData {
    private int j = 100;

    public synchronized void increment() {
        j++;
        System.out.println("increment(): " + j);
    }

    public synchronized void decrement() {
        j--;
        System.out.println("decrement(): " + j);
    }
}


你可能感兴趣的:(thread,面试,String,Class)