public class addSubThread {
/*
* 題目:用JAVA寫一個多線程程序,寫四個線程,其中二個對一個變量加1,另外二個對一個變量減1
* 兩個問題:
* 一、線程同步--synchronized
* 二、線程之間如何共享同一個j變量--內部類
*/
private int i = 100;
/** 加一方法 */
public synchronized void addOne(){
i++;
System.out.println(Thread.currentThread().getName() + "----> addOne:" + i);
}
/** 減一方法 */
public synchronized void subOne(){
i--;
System.out.println(Thread.currentThread().getName() + "----> subOne:" + i);
}
class addThread implements Runnable{java
@Override
public void run() {
addOne();
}
}多線程
class subThread implements Runnable{ide
@Override
public void run() {
subOne();
}
}
public static void main(String[] args) {
addSubThread re = new addSubThread();
addThread aT = re.new addThread();
subThread sT = re.new subThread();
for(int i=0; i<2; i++){
Thread addThread = new Thread(aT);
addThread.start();
Thread subThread = new Thread(sT);
subThread.start();
}
}
}
用java寫一個多線程程序,其中兩個對一個變量加1,另兩個對一個變量減1.net