设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。考虑到线程的安全性写出程序。
/**
* 创建四个线程。两个每次对j加一,两个每次对j减一。考虑线程安全
*/
public class ThreadWork4 {
private int j;
//通过synchronized关键字控制线程同步,即加锁
private synchronized void increaceJ(){//做加一操作
j++;
System.out.println(Thread.currentThread().getName()+"对j加一后;j="+j);
}
private synchronized void decreaceJ(){//做减一操作
j--;
System.out.println(Thread.currentThread().getName()+"对j减一后;j="+j);
}
//编写两个内部类实现Runnable接口,并循环30次
class Thread1 implements Runnable{
@Override
public void run() {
for(int i=0;i<30;i++)
increaceJ();
}
}
class Thread2 implements Runnable{
@Override
public void run() {
for(int i=0;i<30;i++)
decreaceJ();
}
}
public static void main(String[] args) {
ThreadWork4 threadWork4 = new ThreadWork4();
//Thread1和Thread2是内部类,所以使用本类.new 方法创建内部类对象
//如果将内部类设置为静态(static)类就不用这么麻烦了。但是目前正处在学习阶段,还是要掌握多一点
Thread1 thread1 = threadWork4.new Thread1();
Thread1 thread2 = threadWork4.new Thread1();
Thread2 thread3 = threadWork4.new Thread2();
Thread2 thread4 = threadWork4.new Thread2();
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
Thread t3 = new Thread(thread3);
Thread t4 = new Thread(thread4);
t1.start();
t2.start();
t3.start();
t4.start();
}
}