黑马程序员技术交流社区
标题:
java测试题2
[打印本页]
作者:
yepeng0311
时间:
2016-3-22 10:04
标题:
java测试题2
设计
4
个线程,其中两个线程每次对
j
增加
1
,另外两个线程对
j
每次减少
1
。写出程序。
以下程序使用内部类实现线程,对
j
增减的时候没有考虑顺序问题。
作者:
xinzhang
时间:
2016-3-22 13:24
public class Test2 {
public static void main(String[] args) {
Factory factory = new Factory();
T1 t1 = new T1(factory);
T2 t2 = new T2(factory);
Thread thread1 = new Thread(t1, "加线程1");
Thread thread2 = new Thread(t1, "加线程2");
Thread thread3 = new Thread(t2, "减线程1");
Thread thread4 = new Thread(t2, "减线程2");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
class T1 implements Runnable {
Factory factory = null;
T1(Factory factory) {
this.factory = factory;
}
@Override
public void run() {
while (true) {
factory.add();
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class T2 implements Runnable {
Factory factory = null;
T2(Factory factory) {
this.factory = factory;
}
@Override
public void run() {
while (true) {
factory.min();
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Factory {
int j;
Factory() {
j = 0;
}
synchronized void add() {
j++;
System.out.println(Thread.currentThread().getName()+":"+j);
}
synchronized void min() {
j--;
System.out.println(Thread.currentThread().getName()+":"+j);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2