欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java多线程读写文件示例

程序员文章站 2024-02-25 18:38:27
复制代码 代码如下:package com.ysh.file; import java.util.arraylist;import java.util.linkedlis...

复制代码 代码如下:

package com.ysh.file;

import java.util.arraylist;
import java.util.linkedlist;
import java.util.list;
import java.util.concurrent.locks.condition;
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;

import com.google.common.collect.lists;

public class writequeue {
 private static final int max_queue_size = 10000;
 private linkedlist<string> queuecache = lists.newlinkedlist();
 private lock lock = new reentrantlock();
 private condition full = lock.newcondition();
 private condition empty = lock.newcondition();

 private writequeue() {
 }

 private static class writequeueholder {
  private final static writequeue instance = new writequeue();
 }

 public static writequeue getinstance() {
  return writequeueholder.instance;
 }

 public void add(string line) {
  lock.lock();
  try {
   while (queuecache.size() >= max_queue_size) {
    full.await();
   }
   queuecache.addfirst(line);
   empty.signal();
  } catch (interruptedexception e) {
   e.printstacktrace();
  } finally {
   lock.unlock();
  }
 }

 public void add(list<string> linelist) {
  lock.lock();
  try {
   while (queuecache.size() >= max_queue_size) {
    full.await();
   }
   queuecache.addall(linelist);
   empty.signal();
  } catch (interruptedexception e) {
   e.printstacktrace();
  } finally {
   lock.unlock();
  }
 }

 public arraylist<string> flush() {
  arraylist<string> temp = null;
  lock.lock();
  try {
   while (queuecache.size() == 0) {
    empty.await();
   }
   temp = lists.newarraylist();
   temp.addall(queuecache);
   queuecache.clear();
   full.signal();
  } catch (interruptedexception e) {
   e.printstacktrace();
  } finally {
   lock.unlock();
  }
  return temp;
 }

}