package com.imooc;/**?* 設計4個線程,其中兩個線程每次對j增加1,另外兩個線程對j每次減少1。寫出程序。?* @author Administrator?*?*/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(); } } } }
添加回答
舉報
0/150
提交
取消