⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 consumer.java

📁 java可以实现内存共享的
💻 JAVA
字号:
package sharememory;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;


public class Consumer extends Thread
{
    private String mFileName;
    private FileChannel mFileChannel;
    private MappedByteBuffer mMappedByteBuffer;

    public Consumer(String fn)
    {
        try
        {
            mFileName=fn;

            // 获得一个可读写的随机存取文件对象
            RandomAccessFile RAFile=new RandomAccessFile(mFileName,"r");

            // 获得相应的文件通道
            mFileChannel=RAFile.getChannel();

            // 取得文件的实际大小,以便映像到共享内存
            int size=(int)mFileChannel.size();

            // 获得共享内存缓冲区,该共享内存可读
            mMappedByteBuffer=mFileChannel.map(FileChannel.MapMode.READ_ONLY,0,size).load();
        }
        catch(IOException ex)
        {
            System.out.println(ex);
        }
    }

    public void run()
    {
        int i = 0;
        while(true)
        {
            try
            {
                Thread.sleep(300);
                FileLock lock=null;
                lock=mFileChannel.tryLock(0,0,true);
                if(lock==null)
                {
                    System.err.println("Consumer: lock failed");
                    continue;
                }
                Thread.sleep(200);
                System.out.println("Consumer: "+mMappedByteBuffer.getInt(i)+":"+mMappedByteBuffer.getInt(i + 4)+":"+mMappedByteBuffer.getInt(i + 8));
                lock.release();
                i += 4;
            }
            catch(IOException ex)
            {
                System.out.print(ex);
            }
            catch(InterruptedException ex)
            {
                System.out.print(ex);
            }
        }
    }

    public static void main(String args[])
    {
        Consumer consumer=new Consumer("sharedMemory.bin");
        consumer.start();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -