package cn.usst.DataTest6; /** * 设计四个线程,当中共两个线程每次对j添加1,另外两个线程每次对j降低1。循环100次,写出程序。 * @ * */ public class DataTest6 { private int j; public static void main(String[] args) { DataTest6 dt = new DataTest6(); Inc inc = dt.new Inc(); Dec dec = dt.new Dec(); for(int i=0;i < 2; i++){ Thread t = new Thread(inc); t.start(); t = new Thread(dec); t.start(); } } 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(); } } } 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); } }
时间: 2024-10-25 23:58:58