当前位置 : 主页 > 编程语言 > c++ >

生产者消费者模式使用队列

来源:互联网 收集:自由互联 发布时间:2021-07-03
Consumer.java public class Consumer implements Runnable {private final BlockingQueue sharedQueue;public Consumer(BlockingQueue sharedQueue) {this.sharedQueue = sharedQueue;}public void run() {while (true) {try {sharedQueue.take();} catch (I
Consumer.java
public class Consumer implements Runnable {
	private final BlockingQueue sharedQueue;

	public Consumer(BlockingQueue sharedQueue) {
		this.sharedQueue = sharedQueue;
	}

	public void run() {
		while (true) {
			try {
				sharedQueue.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
ProductStorage.java
public class ProductStorage {
	private static BlockingQueue
 
   sharedQueue = new ArrayBlockingQueue
  
   (20); public static void copyFolder(String newPath, String oldPath) { try { File file = new File(newPath); if (!file.exists()) { file.mkdir(); } SmbFile oldFile = new SmbFile(oldPath); String[] files = oldFile.list(); SmbFile temp = null; for (int i = 0; i < files.length; i++) { if (oldPath.endsWith("/")) { temp = new SmbFile(oldPath + files[i]); } else { temp = new SmbFile(oldPath + File.separator + files[i]); } if (temp.isFile()) { InputStream input = new BufferedInputStream(new SmbFileInputStream(temp)); OutputStream output =new BufferedOutputStream(new FileOutputStream(newPath + File.separator + (temp.getName()).toString())); byte[] b = new byte[1024 * 5000]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); b = new byte[1024 * 5000]; } output.close(); input.close(); } sharedQueue.put(files[i]); if (temp.isDirectory()) { copyFolder(newPath + File.separator + files[i], oldPath + files[i] + "/"); } } } catch (Exception e) { e.printStackTrace(); } } public static void startProductThread(){ System.out.println("--生产者线程执行开始--"); int pThreadSize = 4; ExecutorService pool = Executors.newFixedThreadPool(pThreadSize); for(int i=0;i
    
    
     Producter.java
     
    
public class Producter implements Runnable {
	private final BlockingQueue
     
       sharedQueue;

	public Producter(BlockingQueue
      
        sharedQueue) { this.sharedQueue = sharedQueue; } public void run() { Path path = new Path("E://xxx","smb://xxx:xxx@192.168.233.180/xxx/xxx/"); String newPath = path.getNewPath(); String oldPath = path.getOldPath(); ProductStorage.copyFolder(newPath, oldPath); } }
      
     
Test.java
public class Test {

	public static void main(String[] args) {
		ProductStorage.startProductThread();
		ProductStorage.startConsumThread();
	}

}
网友评论