The process of implementing a custom synchronization component in Java

Source: Internet
Author: User

Implement synchronization Component Twinslock: You can allow two threads to acquire the lock at the same time, and the extra threads will be blocked.

The following is a custom synchronization component class, in general we define the custom Synchronizer sync as the static inner class of the synchronization component Twinslock.

Implementing the Synchronizer requires inheriting the Abstractqueuedsynchronizer and overwriting the appropriate method.

Package com.lock;

Import Java.util.concurrent.TimeUnit;
Import Java.util.concurrent.locks.AbstractQueuedSynchronizer;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;

public class Twinslock implements Lock {
Private final Sync sync=new sync (2);
Customize a Synchronizer as a static inner class for a custom synchronization component
Private static final class Sync extends abstractqueuedsynchronizer{
Sync (int count) {
if (count<=0) {
throw new IllegalArgumentException ("Count must large than zero");
}
SetState (count);//Set synchronization status

}
/**
* Try to get sync status in shared mode
* Return is greater than 0 for success
*/
@Override
public int tryacquireshared (int reducecount) {
for (;;) {
int current=getstate ();
int newcount=current-reducecount;
if (newcount<0| | Compareandsetstate (current, newcount)) {
return newcount;
}
}
}
/**
* Method of releasing the synchronization state in the Synchronizer
*/
@Override
public boolean tryreleaseshared (int returncount) {
for (;;) {
int current=getstate ();
int newcount=current+returncount;
if (Compareandsetstate (current, newcount)) {
return true;
}
}
}
}

@Override
public void Lock () {
Sync.acquireshared (1);
}

@Override
public void unlock () {
Sync.releaseshared (1);
}


@Override
public void lockinterruptibly () throws Interruptedexception {
TODO auto-generated Method Stub

}

@Override
Public Condition newcondition () {
TODO auto-generated Method Stub
return null;
}

@Override
public Boolean trylock () {
TODO auto-generated Method Stub
return false;
}

@Override
public boolean Trylock (Long arg0, Timeunit arg1)
Throws Interruptedexception {
TODO auto-generated Method Stub
return false;
}

}

The following is a test class that distinguishes between thread-sharing variables when placing a thread-implementation class inside a method and outside a method

1,

Package com.lock;

Import Java.util.concurrent.locks.Lock;

public class Twinslocktest {

public static void Main (string[] str) throws Interruptedexception {
Place inner classes inside methods, shared variables must be defined as final
Final Lock twinslock=new Twinslock ();
Class Worker extends thread{
public void Run () {
while (true) {
Twinslock.lock ();

try{
Thread.Sleep (10000);
System.out.println (Thread.CurrentThread (). GetName ());
Thread.Sleep (10000);
}catch (Exception e) {
E.printstacktrace ();
}finally{
Twinslock.unlock ();
}
}
}

}
for (int i=0;i<10;i++) {
Worker worker=new Worker ();
Worker.setdaemon (TRUE);
Worker.start ();
}
for (int i=0;i<10;i++) {
Thread.Sleep (500000);
System.out.println ("............");
}

}

}

2,

Package com.lock;

Import Java.util.concurrent.locks.Lock;

public class TwinsLockTest2 {
The external class is placed outside the method, and the shared variable must be defined as static to guarantee synchronization. Otherwise, each thread object will have a copy of the shared variable
Static Lock twinslock=new twinslock ();
public static void Main (string[] str) throws Interruptedexception {


for (int i=0;i<10;i++) {
Worker Worker=new TwinsLockTest2 (). New Worker ();
Worker.setdaemon (TRUE);
Worker.start ();
}
for (int i=0;i<10;i++) {
Thread.Sleep (500000);
System.out.println ("............");
}

}

Class Worker extends thread{
public void Run () {
while (true) {
Twinslock.lock ();

try{
Thread.Sleep (2000);
System.out.println (Thread.CurrentThread (). GetName ());
Thread.Sleep (2000);
}catch (Exception e) {
E.printstacktrace ();
}finally{
Twinslock.unlock ();
}
}
}

}

}

The process of implementing a custom synchronization component in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.