StudyNote--X--JAVA--I
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package trans;
import java.io.*;
import java.util.regex.*;
import java.util.LinkedList;
import java.lang.Thread.*;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* @author sc
*/
//this is a stack which length is only 2
class ProductTable {
//define a LinkedList and then will be used as the stac
public LinkedList <String>products = new LinkedList<String>();
//this is the function to add data into LinkedList,synchronized is the key word used with lock
public synchronized void addProduct(String context){
//if the stack is full,the producer should wait until there is a space
while(this.products.size()>=2){
try {
wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
this.products.addLast(context);
//tell other producer thread they can use this stack now
this.notifyAll();
}
//this function is to get data from the stack
public synchronized String getProduct() {
//if this stack is empty,consumer should wait until some producer filled it
while(this.products.size()<= 0){
try {
wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
String context =this.products.removeFirst();
this.notifyAll();//tell other consumer thread they can use this stack now
return context;
}
}
//this is producer function that implement Runnable function
class Producer implements Runnable {
private ProductTable productTable;
private String context;
private File file;
private BufferedReader input;
//initialize this producer thread
public Producer(ProductTable productTable,String filename) {
this.productTable = productTable;
this.file=new File(filename);//bind the file with filename
if(this.file.exists()){
try{
this.input = new BufferedReader(new FileReader(this.file));
}
//this is required to catch IOException
catch(IOException ioException){
ioException.printStackTrace();
}
}
else{
System.err.println("Does not exist!");
}
}
@Override//override the Runnable run() function
public void run(){
try{
//each time read one line from the file
while((this.context = this.input.readLine())!=null){
this.productTable.addProduct(context);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
this.input.close();//when all data is read,close the file
//send a signal to consumer to tell it the producer is terminated
this.productTable.addProduct("OVER");
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
}
//this is the consumer thread class
class consumerDoc implements Runnable{
private ProductTable productTable;
public StringBuffer[] buffer;
private String str;
private String regex;
private Pattern p;
private Matcher m;
public int count=0;
public consumerDoc(ProductTable productTable){
this.productTable = productTable;
this.str=null;
//this is the pattern match,regression
this.regex="(.*?)(, size)\\ (.+?)\\ [(^](.*?)\\ words(.*?)\\:\\ (.*)";
this.p= Pattern.compile(this.regex);
}
@Override
public void run(){
try{
while(true){
try{
Thread.sleep(1);//thread sleep
this.str=productTable.getProduct();//get a data line from the stack
//if meets "OVER" means producer is terminated and this is the end of the stack,consumer can terminated itself
if(this.str.equals("OVER")){
productTable.addProduct("OVER");//put back to end other threads
return;
}
this.m=this.p.matcher(this.str);
while(m.find()){
//invoke another method and add the filtered information into output data structure
setValue(m.group(1),m.group(4),m.group(6));
}
//must catch InterruptedException in Runnable run() function
}catch(InterruptedException e){
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void setValue(String A,String B,String C){
//this is Main static variable to be invoked here
// not use append twice because of the multi-threads issue
Main.docBuffer[0].append(m.group(1)+"\n");//size
Main.docBuffer[1].append(m.group(4)+"\n");//words
Main.docBuffer[2].append(m.group(6)+"\n");//name
}
}
//this is main class
public class Main {
//three static variables to be invoked, as Runnable has no return method,use this way to get Runnable results
public static LinkedList<String> list = new LinkedList<String>();
public static StringBuffer[] docBuffer=new StringBuffer[3];
public static StringBuffer[] featureBuffer=new StringBuffer[2];
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
// TODO code application logic here
//Use currentTimeMillis() to read current time to measure program proformance
long s=System.currentTimeMillis();
for(int i=0;i<3;i++){
docBuffer[i]=new StringBuffer();
}
featureBuffer[0]=new StringBuffer();
featureBuffer[1]=new StringBuffer();
ProductTable queueA=new ProductTable();
Producer producerA=new Producer(queueA, "C:\\DocInfo.txt");
//start 20 consumer threads to handle the data
consumerDoc[] consumerA=new consumerDoc[20];
for(int i=0;i<20;i++){
consumerA[i]=new consumerDoc(queueA);//initialize the threads
}
Thread threadRQA1=new Thread(producerA);
Thread[] threadRQA2=new Thread[20];
for(int i=0;i<20;i++){
threadRQA2[i]=new Thread(consumerA[i]);
}
threadRQA1.start();//start the thread
for(int i=0;i<20;i++){
threadRQA2[i].start();
}
threadRQA1.join();//only threadRQA1 complete can the rest runs
for(int i=0;i<20;i++){
threadRQA2[i].join();
}//wait for all threads ends
long f=System.currentTimeMillis();
System.out.println("Running time is :"+(f-s));
}
}
**Note to end producer and consumer thread,one should have signal transferred and end according to the signal.Sometimes,multi-threads performance not much better than single thread as frequently access IO would possibly reduce the speed and when use multi-threads, the data order is a big issue that should be considered.
