设计 4 个线程, 其中两个线程每次对 j 增加 1, 另外两个线程对 j 每次减少 1。 写出程序。
1 package mystudy; 2 3 public class ManyThreads { 4 5 private int j; 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 ManyThreads many = new ManyThreads(); 10 Inc inc = many.new Inc(); 11 Dec dec = many.new Dec(); 12 for (int i = 0; i < 2; i++) { 13 Thread t = new Thread(inc); 14 t.start(); 15 t = new Thread(dec); 16 t.start(); 17 } 18 } 19 20 private synchronized void inc() { 21 j++; 22 System.out.println(Thread.currentThread().getName() + "inc" + j); 23 } 24 25 private synchronized void dec() { 26 j--; 27 System.out.println(Thread.currentThread().getName() + "dec" + j); 28 } 29 30 class Inc implements Runnable { 31 32 @Override 33 public void run() { 34 // TODO Auto-generated method stub 35 for (int i = 0; i < 20; i++) { 36 inc(); 37 } 38 } 39 40 } 41 42 class Dec implements Runnable { 43 44 @Override 45 public void run() { 46 // TODO Auto-generated method stub 47 for (int i = 0; i < 20; i++) { 48 dec(); 49 } 50 } 51 52 } 53 }
第二种
时间: 2024-12-13 00:11:11