最近在看面试题,记录一个多线程同步的简单程序,略有改动
package learning;
/**
* @author john 设计 4 个线程,其中两个线程每次对 j 增加 1 ,另外两个线程对 j 每次减少 1 。写 出程序
*/
public class TestThread {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
Thread inc = new Thread(new Inc());
Thread dec = new Thread(new Dec());
inc.start();
dec.start();
}
}
}
//创建+1线程的类,实现Runnable接口
class Inc implements Runnable {
private int j;
//synchronized修饰+1的同步方法,输出线程名称和j的值
public synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "-inc:" + j);
}
@Override
public void run() {
// TODO Auto-generated method stub
//实现Runnable的run方法,调用inc方法
this.inc();
}
}
class Dec implements Runnable {
private int j;
public synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "-dec:" + j);
}
public void run() {
this.dec();
}
}