Results 1 to 3 of 3
  1. #1
    StevenTNorris is offline Member
    Join Date
    Oct 2011
    Posts
    9
    Rep Power
    0

    Exclamation Multi-threading issue

    I haven't used multithreading in about a year, but I believe I'm doing it at least close to correct. I have a class implementing runnable. Creating a new thread with that runnable, and start(). No go. I get the run without error, but as if it's all running from the main thread. My intent is to run a document scanning script in the background while a "Scanning..." appears with blinking dots while it runs. (this will be expanded on later, but i need that first). Code below. Any help would be great.


    PORTION OF CODE USING THE RUNNABLE
    Java Code:
    /**
    		 * Listener for scanning merges
    		 * 
    		 * 
    		 * @author stnorris
    		 *
    		 */
    		class scanListener implements ActionListener{
    
    			private JFrame parent;
    			private int type;
    			public static final int FOLDER = 2;
    			public static final int LIBRARY = 1;
    			public static final int FILE = 0;
    			
    			/**
    			 * Constructs a listener for scanning
    			 * 
    			 * @param parent parent frame
    			 * @param type type of scan
    			 */
    			public scanListener(JFrame parent,int type){
    				this.parent=parent;
    				this.type = type;
    			}
    			
    			@Override
    			public void actionPerformed(ActionEvent arg0) {
    				fileChooser.setDialogTitle("Scan");
    				int result = -1;
    				if(type == FOLDER){
    					fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    					result = fileChooser.showDialog(parent,"Scan folder");
    				}
    				else if(type == LIBRARY){
    					fileChooser.setFileFilter(hdlFilter);
    					fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    					result = fileChooser.showDialog(parent,"Scan library file");
    				}
    				else if(type == FILE){
    					fileChooser.setFileFilter(rtfFilter);
    					fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    					result = fileChooser.showDialog(parent,"Scan single file");
    				}
    				if(result == JFileChooser.APPROVE_OPTION){
    					viewPanel.removeAll();
    					if(type == FOLDER){
    						control.setSource(fileChooser.getSelectedFile().getPath()+"\\");
    					}
    					else{
    						control.setSource(fileChooser.getSelectedFile().getPath());
    					}
    					Thread tempThread = new Thread(control);
    					tempThread.start();
    					JLabel tempLabel = new JLabel("Scanning");
    					int count = 1;
    					while(tempThread.isAlive()){
    						System.out.println("main thread: "+count);
    						if(count == 4){
    							tempLabel.setText("Scanning");
    						}
    						for(int i=0;i < count; i++){
    							tempLabel.setText(tempLabel.getText()+".");
    						}
    						viewPanel.add(tempLabel);
    						viewPanel.updateUI();
    						try {
    							Thread.currentThread().sleep(3000);
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    					}
    					locationField.setText(fileChooser.getSelectedFile().getPath());
    					debugBox.setEnabled(true);
    					exportButton.setEnabled(true);
    					saveMenu.setEnabled(true);
    					exportMenu.setEnabled(true);
    					editMenu.setEnabled(true);
    					viewPanel.removeAll();
    					populateViewPane(viewPanel, control.getNode(),0);
    				}
    			}
    			
    		}
    		
    		
    		//Add listeners to menus and buttons
    		scanFolderMenu.addActionListener(new scanListener(this, scanListener.FOLDER));
    		openMenu.addActionListener(new openListener(this));
    		saveMenu.addActionListener(new saveListener(this));
    		exportMenu.addActionListener(new exportListener(this));
    		scanLibraryMenu.addActionListener(new scanListener(this, scanListener.LIBRARY));
    		scanFileMenu.addActionListener(new scanListener(this,scanListener.FILE));
    		findMenu.addActionListener(new findListener(this));
    		insertedRegMenu.addActionListener(new insertedListener(this,false));
    		insertedDeepMenu.addActionListener(new insertedListener(this,true));
    		findButton.addActionListener(new findListener(this));
    		exportButton.addActionListener(new exportListener(this));
    		imageMenu.addActionListener(new imageListener(this));
    
    	}
    RUNNABLE CLASS
    Java Code:
    package si.classes;
    
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.ObjectInputStream;
    import java.util.ArrayList;
    import java.util.Hashtable;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import si.abstracts.Node;
    import si.commandline.CommandLineRunner;
    
    /**
     * Used to control the building and writing of a hot doc insert tree
     * 
     * @author stnorris
     */
    public class HotDocTreeWriterController implements Runnable{
    	
    	private final HotDocTreeScraper scraper=new HotDocTreeScraper();
    	private final DocNodeWriter writer = DocNodeWriter.getInstance();
    	private static Logger log = Logger.getLogger(CommandLineRunner.class.getName());
    	private ArrayList<Node>tempExists = new ArrayList<Node>();
    	
    	/**
    	 * Creates the controller
    	 */
    	public HotDocTreeWriterController(){
    		log.setLevel(Level.INFO);
    	}
    	
    	/**
    	 * Sets the level for the logger
    	 * 
    	 * @param level level for logging
    	 */
    	public void setLogLevel(Level level){
    		log.setLevel(level);
    		scraper.setLogLevel(level);
    		writer.setLogLevel(level);
    	}
    	
    	/**
    	 * Adds errors to the error log
    	 * 
    	 * @param errors
    	 */
    	public void addToErrorLog(String errors){
    		writer.addToErrorLog(errors);
    	}
    	
    	/**
    	 * Sets source directory for scraper
    	 * 
    	 * @param directory
    	 */
    	public void setSource(String directory){
    		scraper.setSource(directory);
    	}
    	
    	/**
    	 * Sets location for writer
    	 * 
    	 * @param location
    	 */
    	public void setLocation(String location){
    		writer.setLocation(location);
    	}
    	
    	/**
    	 * Sets node for writer
    	 * 
    	 * @param node
    	 */
    	public void setNode(DocNode node){
    		writer.setNode(node);
    	}
    	
    	/**
    	 * Sets node based on an hdt file
    	 * 
    	 * @param nodeFile hdt file of node
    	 */
    	public void setNode(File nodeFile){
    		try {
    			FileInputStream inStream = new FileInputStream(nodeFile);
    			ObjectInputStream oIn = new ObjectInputStream(inStream);
    			DocNode node = (DocNode) oIn.readObject();
    			writer.setNode(node);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		}
    		
    	}
    	
    	public Hashtable<String,Node> getChildren(Node node){
    		Hashtable<String,Node> children = new Hashtable<String,Node>();
    		for(Node tempNode:node.getChildren()){
    			children.put(tempNode.getName(), tempNode);
    		}
    		return children;
    	}
    	
    	public DocNode getNode(){
    		return writer.getNode();
    	}
    	
    	/**
    	 * Sets doc name for writer
    	 * 
    	 * @param name
    	 */
    	public void setDocName(String name){
    		writer.setDocName(name);
    	}
    	
    	/**
    	 * Builds inserts tree
    	 */
    	public void buildTree(){
    		scraper.scrape();
    		writer.setNode(scraper.getResult());
    		writer.addToErrorLog("\r\r"+scraper.getErrors());
    	}
    	
    	/**
    	 * Checks for images in documents
    	 * 
    	 * @return String list of documents containing images
    	 */
    	public String checkImage(){
    		DocNode node = writer.getNode();
    		ArrayList<DocNode> children = node.getDocChildren();
    		String tempBuild;
    		String line;
    		FileInputStream in;
    		DataInputStream inData;
    		InputStreamReader inStream;
    		BufferedReader buffIn;
    		String errorFile = node.getFile().getPath();
    		tempBuild = "Images are in: ";
    		try {
    			log.log(Level.INFO,"Finding images...");
    			for(DocNode child:children){
    				errorFile = child.getFile().getAbsolutePath();
    				in = new FileInputStream(child.getFile());
    				inData = new DataInputStream(in);
    				inStream = new InputStreamReader(inData);
    				buffIn = new BufferedReader(inStream);
    				log.log(Level.INFO,"Finding images for "+child.getName()+"...");
    				while((line = buffIn.readLine()) != null){
    					if(line.contains("\\pict")){
    						tempBuild += "\n" + child.getName();
    						break;
    					}
    					
    				}
    			}
    			if(tempBuild.equals("Images are in: ")){
    				return null;
    			}
    			else{
    				return tempBuild;
    			}
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    			return "File read error! : "+errorFile;
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			return "File read error! : " + errorFile;
    		}
    	}
    	
    	/**
    	 * Writes files
    	 */
    	public void write(){
    		writer.write();
    	}
    	
    	/**
    	 * Writes files according to given parameters
    	 * @param text
    	 * @param object
    	 * @param error
    	 */
    	public void write(boolean text, boolean object, boolean error){
    		writer.write(text,object,error);
    	}
    	
    	/**
    	 * Checks node for inserts in top level or deep mode
    	 * 
    	 * @param node node to be checked
    	 * @param name name to check for
    	 * @param deepSearch deep or top level search
    	 * @return arraylist of inserts
    	 */
    	private void innerCheckInsert(Node node, String name, boolean deepSearch, ArrayList<String> insertions){
    		ArrayList<Node> innerChildren = node.getChildren();
    		if(!tempExists.contains(node)){
    			tempExists.add(node);
    			for(Node child2:innerChildren){
    					if(!insertions.contains(node.getName()) && name.equalsIgnoreCase(child2.getName())){
    						insertions.add(node.getName());
    					}
    					if(deepSearch){
    						innerCheckInsert(child2,name,deepSearch,insertions);
    					}
    			}
    		}
    	}
    	
    	/**
    	 * Checks to see if the name is inserted into any of the node's children's children
    	 * 
    	 * @param name name to check for
    	 * @param node node to use for checking
    	 * @return
    	 */
    	public ArrayList<String> checkInserted(String name, boolean deepSearch){
    		ArrayList<String>insertions = new ArrayList<String>();
    		ArrayList<Node>tempChildren = writer.getNode().getChildren();
    		tempExists.clear();
    		for(Node child:tempChildren){
    			innerCheckInsert(child,name,deepSearch,insertions);
    		}
    		if(insertions.size()>0){
    			return insertions;
    		}
    		else{
    			return null;
    		}
    	}
    
    	@Override
    	public void run() {
    		buildTree();		
    	}
    }

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default Re: Multi-threading issue

    Java Code:
    Thread tempThread = new Thread(control);
    tempThread.start();
    What is control? I can't find where it's being declared or passed in.
    Get in the habit of using standard Java naming conventions!

  3. #3
    StevenTNorris is offline Member
    Join Date
    Oct 2011
    Posts
    9
    Rep Power
    0

    Default Re: Multi-threading issue

    control is a HotDocTreeWriterController. I believe the issue was with the updateUI();. It seemed the while loop wouldn't allow dynamic updating of the UI while it ran, but only after it was finished running. Removing the while loop and just using a static "Scanning..." without trying to make the dots move worked fine.

Similar Threads

  1. multi-threading problem
    By imorio in forum New To Java
    Replies: 1
    Last Post: 04-25-2011, 06:52 PM
  2. Simple question about multi-threading
    By intrepid604 in forum New To Java
    Replies: 0
    Last Post: 03-07-2011, 10:20 PM
  3. Need Help! Multi-Threading question!
    By pinkette in forum New To Java
    Replies: 8
    Last Post: 01-13-2011, 07:08 PM
  4. Problem in Multi threading.
    By Chetans in forum Advanced Java
    Replies: 3
    Last Post: 03-23-2010, 04:42 PM
  5. question about Multi threading in Java
    By fred in forum Advanced Java
    Replies: 1
    Last Post: 07-24-2007, 01:55 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •