ooops, been spending some time on this. wondering the skills.

package com.test;

import java.util.ArrayList;

public class Lock {

	private static volatile int xFlag = 0;
	private static volatile Lock xLock = new Lock();

	private static volatile int topPrio = -1;
	private static volatile ArrayList waitingThreads = new ArrayList();

	public static void lock() {
		synchronized (xLock) {
			while (true) {
				if (xFlag == 0 && waitingThreads.isEmpty()) {
					xFlag = 1;
					return;
				} else if (xFlag == 0 && !waitingThreads.isEmpty()) {
					for (Thread t : waitingThreads) {
						if (t.getPriority() > topPrio)
							topPrio = t.getPriority();
					}

					if (Thread.currentThread().getPriority() >= topPrio) {
						xFlag = 1;
						waitingThreads.clear();// reset waitingThreads
						topPrio = -1; // reset topPrio
						xLock.notifyAll();
						return;
					}
					
					try {
						xLock.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				} else {
					try {
						waitingThreads.add(Thread.currentThread());
						xLock.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static void unlock() {
		synchronized (xLock) {
			xFlag = 0;
			xLock.notifyAll();
		}
	}

}

Advertisements

Author: lwpro2

Java J2EE professional

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s