单机上多JVM同步控制的一种方法(2)

public static void testLock(){
        RandomAccessFile f1=null;
        RandomAccessFile f2=null;
       
        FileChannel channel1=null;
        FileChannel channel2=null;
       
        FileLock lock1=null;
        FileLock lock2=null;
       
        try {
            f1=new RandomAccessFile("test.txt","rw");
            //f1.writeChars("asd");
            channel1 = f1.getChannel();
           
            lock1 = channel1.lock();
            if(lock1!=null) System.out.println("1:success");
            else System.out.println("1:fail");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
        try {
            f2=new RandomAccessFile("test.txt","rw");
            //f2.writeChars("123");
            channel2 = f1.getChannel();
           
            lock2 = channel2.lock();
           
            if(lock2!=null) System.out.println("1:success");
            else System.out.println("1:fail");
           
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
        try {
            if(lock1!=null) lock1.release();
            if(lock2!=null) lock1.release();
           
            if(channel1!=null) channel1.close();
            if(channel2!=null) channel2.close();
           
           
            if(f1!=null) f1.close();
            if(f2!=null) f2.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
    }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyzwxp.html