本帖最后由 柳 德 彬 于 2013-4-17 21:57 编辑
一个增加的线程,一个减少的线程,启动四个线程实现加1减1 ,,求解,,最后什么也没有输出,,JVM一直在运行。。。。。???
//增加的 Thread- public class Increase implements Runnable {
- private TestThread2 obj;
- public Increase(TestThread2 obj) {
- this.obj = obj;
- }
- public void run() {
- for (int i = 0; i < 20; i++) {
- try {
- Thread.sleep((long) Math.random() * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- obj.inc();
- }
- }
- }
复制代码 //减少的线程- public class Decrease implements Runnable{
- private TestThread2 obj;
- public Decrease(TestThread2 obj){
- this.obj=obj;
- }
- public void run(){
- for (int i = 0; i < 20; i++) {
- try {
- Thread.sleep((long)Math.random()*500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- obj.dec();
- }
- }
- }
复制代码 //加1减1的两个方法- public class TestThread2 {
- private int j;
- public synchronized void inc() {
- if (0 != j) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- j++;
- System.out.println(Thread.currentThread().getName() + "-inc:" + j);
- notify();
- }
- }
- public synchronized void dec() {
- if (0 == j) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- j--;
- System.out.println(Thread.currentThread().getName() + "-dec:" + j);
- notify();
- }
- }
- }
复制代码 // 测试- public class MainClass {
- public static void main(String[] args) {
- TestThread2 t = new TestThread2();
- Thread inc = new Thread(new Increase(t));
- Thread dec = new Thread(new Decrease(t));
- inc.start();
- dec.start();
- }
- }
复制代码 |