开发者

Testing custom lock in Java

I have a MyLock class that implements the Lock interface. Now the constructor in MyLock accepts two Thread objects as parameters.

I am writing a test class for MyLock.

public class TestMyLock
{
    static MyLock mylck;

    public static void main(String[] args)
    {           

        Thread t1 = new Thread(new Runnabl开发者_如何转开发e(){
            public void run(){

                mylck.lock();       //1 - gives error
                            //Critical code

                mylck.unlock();                 
            }

        });
        Thread t2 = new Thread(new Runnable(){
            public void run(){

                mylck.lock();
                            //Critical code                 
                mylck.unlock();                 
            }

        });

        mylck = new MyLock(t1, t2);  //where to place this

        t1.start(); t2.start();

    }
}

Where is my test code going wrong. Basically, I need to test my MyLck functionality.

EDIT: The error -1 is because myLck is not initialized. It gives a compilation error. I would like to know how to initialize this, since to initialize, I need to pass the thread objects.


i think it would be better to put mylck.lock() ... mylck.unlock() in a loop to make it run for longer time to detect flaws if this is feasible. We need to know how's MyLock.lock() is implemented to see what's the error.


I can't see what is wrong with this main class. The lock creation is done before threads are started, thus the mylck reference used in both run methods will not be null when call => it's ok.

On a side note, why do you implement your own lock ? The java.util.concurrent.locks package provides several common implementations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜