1. 程式人生 > >多執行緒——設計4個執行緒,其中兩個執行緒每次對j增加1,另外兩個執行緒對j每次減少1。寫出程式。

多執行緒——設計4個執行緒,其中兩個執行緒每次對j增加1,另外兩個執行緒對j每次減少1。寫出程式。

package com.com.aaa.addreduceThread;

public class ThreadDemo {
    private int j=1;

    //每次新增1
    private synchronized void ad(){
        j++;
        System.out.println("新增"+j);
    }

    //每次減少1
    private synchronized void red(){
        j--;
        System.out.println("減少"+j);
    }

    private
class Add implements Runnable{ @Override public void run() { for (int i=0;i<5;i++){ ad(); } } } private class Reduce implements Runnable{ @Override public void run() { for (int i=0;i<5;i++){ red
(); } } } public static void main(String[] args) { ThreadDemo td=new ThreadDemo(); Thread t=null; Add a=td.new Add(); Reduce r=td.new Reduce(); for (int i=0;i<2;i++){ t=new Thread(a); t.start(); t=
new Thread(r); t.start(); } } }

執行結果: 在這裡插入圖片描述