0
    I have following classes :

    package com.akshu.multithreading;

    public class ThreadResource {

        static int a;
     static boolean Value =false;
        public synchronized int getA() {
            while(Value == false){
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Value= false;
            notify();


            return a;
        }

        public synchronized void setA(int a) {
            while(Value == true)
            {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            ThreadResource.a = a;
            Value=true;
            notify();

        }


    }


    ------------------


    /**
     * 
     */
    package com.akshu.multithreading;

    /**
     * @author akshu
     *
     */
    public class MyThreadA implements Runnable  {

        int a = 0;
        ThreadResource tR= new ThreadResource();

        @Override
        public void run() {


        for (int i = 0; i < 15; i++) {



            tR.setA(++a);
            System.out.println(" value of a :"+a);





        }

        }
    }

    ------------

    package com.akshu.multithreading;

    public class MyThreadB implements Runnable {

        @Override
    public void run() {
        // TODO Auto-generated method stub
        ThreadResource tR =new ThreadResource();
        for (int i = 0; i < 15; i++) {

        System.out.println("getA()"+tR.getA());

                }
    }
    }
    ----

    package com.akshu.multithreading;

    public class ThreadExecutionPoint {

        public static void main(String args[])  {

            Thread th1 = new Thread(new MyThreadA());
            Thread th2 = new Thread(new MyThreadB());

            th1.start();
            th2.start();
        }
    }

上記のコードを使用してプロデューサーの消費者の問題を理解しようとしています。上記のコードを実行すると、

    value of a :1
    getA()1

プログラムはここでのみスタックします (終了しません)。

誰か私がここで何をしているのか説明してください。

4

1 に答える 1

1

つまり、メソッド を 宣言しましValueた。これは、それらがロックオンされていることを意味します(オブジェクトの固有のロック)。 ただし、コードでは、スレッドごとに異なるものをインスタンス化するため、ケースごとに異なるため、スレッドは作成されません。 次のようにコードを変更します。 volatile
static volatile boolean Value =false;
set/getsynchronizedthis
ThreadResourcesynchronizedthis

public class MyThreadA implements Runnable {  
    ThreadResource tR;  

     public MyThreadA(ThreadResource tr) {  
        this.tR = tr;  
    }  
// your run method here NOT declaring a ThreadResource anymore!!!
}   

と同じMyThreadB

その後、ThreadExecutionPoint

ThreadResource tr = new ThreadResource();  
Thread th1 = new Thread(new MyThreadA(tr));  
Thread th2 = new Thread(new MyThreadB(tr));  
于 2013-03-17T17:53:04.080 に答える