Java內存共享就是對同一段內存的讀寫;用來進行進程之間的通信。
首先是寫的代碼:
- package com.sharememory.test;
-
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.nio.MappedByteBuffer;
- import java.nio.channels.FileChannel;
- import java.nio.channels.FileLock;
-
- public class WriteMemory {
- String fileName = "shm.lock";
- RandomAccessFile raFile;
- FileChannel fc;
- int iSize = 1024;
- MappedByteBuffer mapBuf;
- int iMode;
-
- public WriteMemory() {
- try {
- init();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void init() throws Exception {
- raFile = new RandomAccessFile(fileName, "rw");
- fc = raFile.getChannel();
- mapBuf = fc.map(FileChannel.MapMode.READ_WRITE, 0, iSize);
- }
-
- public void clearBuffer() {
- // 清除文件內容
- for (int i = 0; i < 1024; i++) {
- mapBuf.put(i, (byte) 0);
- }
- }
-
- public void putBuffer() throws Exception{
- for (int i = 65; i < 91; i++) {
- int index = i - 63;
- int flag = mapBuf.get(0); // 可讀標置第一個字節為 0
- if (flag != 0) { // 不是可寫標示 0,則重復循環,等待
- i--;
- continue;
- }
- mapBuf.put(0, (byte) 1); // 正在寫數據,標志第一個字節為 1
- mapBuf.put(1, (byte) (index)); // 寫數據的位置
-
- System.out.println("程序 WriteShareMemory:"
- + System.currentTimeMillis() + ":位置:" + index + " 寫入數據:"
- + (char) i);
-
- mapBuf.put(index, (byte) i);// index 位置寫入數據
- mapBuf.put(0, (byte) 2); // 置可讀數據標志第一個字節為 2
- Thread.sleep(513);
- }
- }
-
- public boolean getLock() {
- FileLock lock = null;
- try {
- lock = fc.tryLock();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (lock == null) {
- return false;
- } else {
- return true;
- }
- }
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- WriteMemory map = new WriteMemory();
- if (map.getLock()) {
- try {
- map.putBuffer();
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("can't get lock");
- }
- }
- }