JAVA多线程编程。 用JAVA写一个多线程程序,如写四个线程,二个加1,二个对一个变量减一,输出。
package com.base;
public class ThreadTest {
public static int j = 0;
public static void main(String[] args) {
new ThreadTest_1().start();
new ThreadTest_2().start();
new ThreadTest_3().start();
new ThreadTest_4().start();
System.out.println(j);
}
public synchronized void deleteOne(){
j --;
}
public synchronized void addOne(){
j ++;
}
}
class ThreadTest_1 extends Thread {
@Override
public void run() {
ThreadTest aTest = new ThreadTest();
for (int i = 0; i < 5; i++) {
aTest.deleteOne();
}
}
}
class ThreadTest_2 extends Thread {
@Override
public void run() {
new ThreadTest().deleteOne();
}
}
class ThreadTest_3 extends Thread {
@Override
public void run() {
new ThreadTest().addOne();
}
}
class ThreadTest_4 extends Thread {
@Override
public void run() {
new ThreadTest().addOne();
}
}