Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the first method, I just want to create a thread for each URL in the array and parse it:
public void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for(int x = 0; x< urls.length; x++){
urlThreads[x].start();
}
}
And then I made a separate class for my runnable object, where the run method creates a bufferedReader to scan the html file and parses it.
package twitbook;
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public Runobject(String theAdress, Twitbook net) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
I know when the first method is called, even though I started the threads, it doesn't go through the run method in the runObject class. Why is this?
Your code works perfectly. You simply do not realize it. Add few logging/output messages and you will see it. Oh, by the way, anticipate end of input. Here is simplified code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Runobject implements Runnable {
public String address;
public static void main(String a[]) {
System.out.println("Start");
readFriendData(new String[] { "http://google.com", "http://yahoo.com" });
System.out.println("End");
}
public static void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x]);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for (int x = 0; x < urls.length; x++) {
urlThreads[x].start();
}
}
public Runobject(String theAdress) {
address = theAdress;
System.out.println(address);
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
int countOfLines = 0;
String input = scanner.readLine();
while (input != null && !input.equals("</body>")) {
countOfLines++;
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.friend(bits[0], bits[1]);
// net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
System.out.println(address + " has " + countOfLines + " lines");
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
and here is output:
Start
http://google.com
http://yahoo.com
End
http://google.com has 8 lines
http://yahoo.com has 63 lines
Pay attention that your main thread is already finished when your readers just started yet. One word - multithreading.
Though, I don't like the quality of it. I know I am not code reviewer. Please try this!
public static void main(String[] args) {
Twitbook twitbook = new Twitbook();
String[] urls = new String[2];
urls[0] = "www.google.com";
urls[0] = "www.yahoo.com";
twitbook.readFriendData(urls);
}
public void readFriendData(String[] urls) {
CountDownLatch latch = new CountDownLatch(urls.length);
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this, latch);
input.run();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
public synchronized void addUser(String input) {
return;
}
public synchronized void friend(String bits1, String bits2) {
return;
}
RunObject class here
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public CountDownLatch latch;
public Runobject(String theAdress, Twitbook net, CountDownLatch latch) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
} finally {
latch.countDown();
}
}
Please consider better design. These links may help you to do better coding.
Thread pool is a good option.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
CountDownLatch for finish all threads http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
Runobject can be a private inner class as well.
Wait until child threads completed : Java
disclaimer :- Answered with help of other question and answers.
Related
I tried to implement multithreading in Java by using executor service approach. Here is my code:
public class GetResponseContentWithExecutorService {
private static final int MYTHREADS = 30;
public static void main(String args[]) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
String[] urlList ={"url1", "url2", "url3" ...};
for (int i = 0; i < urlList.length; i++) {
String baseUrl = "myUrl";
Runnable worker = new MyRunnable(baseUrl, urlList[i].split("-")[0], urlList[i].split("-")[1]);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("\nCompleted all threads");
}
}
public class MyRunnable implements Runnable {
private final String baseUrl;
private final String a;
private final String b;
MyRunnable(String baseUrl, String a, String b) {
this.baseUrl = baseUrl;
this.a= a;
this.b= b;
}
#Override
public void run() {
String result = "";
int code = 200;
try {
URL siteURL = new URL(baseUrl + a + b);
HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
connection.connect();
code = connection.getResponseCode();
if (code == 200) {
result = "-> Succ<-\t" + "Code: " + code;
} else {
result = "-> NoSuc <-\t" + "Code: " + code;
}
}
catch (Exception e) {
result = e.getMessage();
}
System.out.println(code);
}
}
The thing is that for about 30 urls I need to wait approx.40seconds and I would like to make it way faster. Any suggestions to what am I doing wrong here?
Any help is appreciated!!
I have 100 sentences of test data. I am trying to run sentiment analysis on them but no matter what input String I am using, I am only getting a positive estimation of the input string. Each sentence gets a return value of 1.0. Any idea why this might be happening? Even if I use negative example inputs from the .txt file, the result is a positive value.
public class StartSentiment
{
public static DoccatModel model = null;
public static String[] analyzedTexts = {"Good win"};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("src\\sentiment\\Results.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "1");
tp.put(TrainingParameters.ITERATIONS_PARAM, "100");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text) throws IOException{
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(text.split(" ") );
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}
I've compiled and debugged my program, but there is no output. I suspect an issue passing from BufferedReader to the array method, but I'm not good enough with java to know what it is or how to fix it... Please help! :)
public class Viennaproj {
private String[] names;
private int longth;
//private String [] output;
public Viennaproj(int length, String line) throws IOException
{
this.longth = length;
this.names = new String[length];
String file = "names.txt";
processFile("names.txt",5);
sortNames();
}
public void processFile (String file, int x) throws IOException, FileNotFoundException{
BufferedReader reader = null;
try {
//File file = new File("names.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sortNames()
{
int counter = 0;
int[] lengths = new int[longth];
for( String name : names)
{
lengths[counter] = name.length();
counter++;
}
for (int k = 0; k<longth; k++)
{
int counter2 = k+1;
while (lengths[counter2]<lengths[k]){
String temp2;
int temp;
temp = lengths[counter2];
temp2 = names[counter2];
lengths[counter2] = lengths[k];
names[counter2] = names[k];
lengths[k] = temp;
names[k] = temp2;
counter2++;
}
}
}
public String toString()
{
String output = new String();
for(String name: names)
{
output = name + "/n" + output;
}
return output;
}
public static void main(String[] args)
{
String output = new String ();
output= output.toString();
System.out.println(output+"");
}
}
In Java, the public static void main(String[] args) method is the starting point of the application.
You should create an object of Viennaproj in your main method. Looking at your implementation, just creating an object of Viennaproj will fix your code.
Your main method should look like below
public static void main(String[] args) throws IOException
{
Viennaproj viennaproj = new Viennaproj(5, "Sample Line");
String output= viennaproj.toString();
System.out.println(output);
}
And, if you are getting a FileNotFound exception when you execute this, it means that java is not able to find the file.
You must provide complete file path of your file to avoid that issue. (eg: "C:/test/input.txt")
I am new at Java and I am having a little trouble:
I am trying to read chemical samples to represent them at a X-Y graph.
The input file looks like this:
La 0.85678
Ce 0.473
Pr 62.839
...
...
My code stocks only the unpair lines value (0.85678, jumps line, 62.839 at the example), and I cannot realize what is the problem:
public class Procces {
public void readREE() throws IOException {
try{
rEE = new BufferedReader (new FileReader ("src/files/test.txt"));
while ( (currentLine = rEE.readLine() ) != null) {
try {
for (int size = 3;size<10;size++) {
String valueDec=(currentLine.substring(3,size));
//char letra =(char)c;
if ((c=rEE.read()) != -1) {
System.out.println("Max size");
} else
valueD = Double.parseDouble(valueDec);
System.out.println(valueDec);
}
}
catch (Exception excUncertainDecimals) {
}
}
}finally {
try { rEE.close();
} catch (Exception exc) {
}
}
}
String line;
int c = 0;
int counter = 0;
String valueS = null;
String valueSimb = null;
Double valueD = null;
Double logValue = null;
Double YFin=450.0;
String currentLine;
BufferedReader rEE;
}
Thank you in advance, as I can't see why the program jumps the pair lines.
use Java Scanner class.
import java.io.*;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) throws IOException {
try (Scanner s = new Scanner(new BufferedReader(new FileReader("file.txt"))){
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
}
Please have a look at Scanner.
In general is Java a well established language and in most cases you do not have to re-implemented "common" (e.g. reading custom text files) stuff on a low level way.
I get it. Thank you.
Here the code:
import java.io.*
import java.util.Scanner;
public class Process implements Samples{
public void readREE() throws IOException {
try
(Scanner rEE = new Scanner(new BufferedReader(new FileReader("src/files/test.txt")))){
while (rEE.hasNext()) {
element = rEE.next();
if (element.equals("La")) {
String elementValue = rEE.next();
Double value = Double.parseDouble(elementValue);
Double valueChond = 0.237;
Double valueNorm= value/valueChond;
Double logValue = (Math.log(valueNorm)/Math.log(10));
Double yLog = yOrd - logValue*133.33333333;
Sample NormedSampleLa=new Sample("La",yLog);
sampleREE.add(NormedSampleLa);
}
}
} finally {
}
}
public String LaS, CeS, PrS, NdS, PmS, SmS, EuS, GdS, TbS, DyS, HoS, ErS, TmS, YbS, LuS;
public String element, elementValue;
public Double yOrd=450.0;
}
I am trying to replace routeName and routeDurationInMinutes but the rpelace method is not working. It was working when i had it outside the run function but inside it does not work. Any ideas? I have added all my code that I am trying to run. Im sorry that this is so back and forth. I tried to shorten it to make it easier for others to read.
The Value g = {"routes":[{"routeName":"I-190 N; Electric Ave","routeDurationInMinutes":70,"routeLengthKM":83.865,"routeLengthMiles":52.111278915,"toll":false},{"routeName":"I-190 N; Greenville Rd","routeDurationInMinutes":82,"routeLengthKM":92.569,"routeLengthMiles":57.519692099000004,"toll":false}],"startPoint":"street address","endPoint":"destination","startLatitude":"42.20115054203528","startLongitude":"-71.85038140607858","endLatitude":"42.201220801535","endLongitude":"-71.849075146695"}
final Runnable rundatapoll = new Runnable() {
#Override
public void run() {
String g;
try {
g = new apicall().execute().get().getBody().toString();
System.out.println(g);
String route1;
String route2;
String time1;
String time2;
String time3;
ArrayList parse= new ArrayList();
ArrayList route= new ArrayList();
ArrayList time= new ArrayList();
Pattern p= Pattern.compile("routeName?.+?routeLengthKM");
Matcher m = p.matcher(g);
Pattern p2= Pattern.compile("routeName?.+?routeDurationInMinutes");
Pattern p3= Pattern.compile("routeDurationInMinutes?.+?routeLengthKM");
Matcher m3= p3.matcher(g);
while (m.find()) {
parse.add(m.group());
}
while (m3.find()){
time.add(m3.group());
}
int l=0;
while (l<parse.size()){
Matcher m2 =p2.matcher((CharSequence) parse.get(l));
while(m2.find()){
route.add(m2.group());
}
l++;
}
//////////////////////////////////////////////////////////////////////////////////////
route1= (String) route.get(0);
route2= (String) route.get(1);
route1= route1.replace(",routeDurationInMinutes","");
route1= route1.replace("routeName:","");
route2= route2.replace(",routeDurationInMinutes","");
route2= route2.replace("routeName:","");
time1= (String) time.get(0);
time2= (String) time.get(1);
time1= time1.replace("routeDurationInMinutes:","");
time1= time1.replace(",routeLengthKM","");
time2= time2.replace("routeDurationInMinutes:","");
time2= time2.replace(",routeLengthKM","");
t1.setValue(time1);
t2.setValue(time2);
r1.setValue(route1);
r2.setValue(route2);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
};
>>>routeName":"I-190 N; Electric Ave","routeDurationInMinutes
Looks like the thread might not be being executed as suggested in the comments.
This worked for me:
package example;
public class Example {
final String g="routeName:I-190 N; Electric Ave,routeDurationInMinutes";
final Runnable rundatapoll = new Runnable() {
#Override
public void run() {
String route1=g;
System.out.println("BEFORE THREAD");
System.out.println(route1);
route1= route1.replace(",routeDurationInMinutes","");
route1= route1.replace("routeName:","");
System.out.println("AFTER RUNNING THREAD:");
System.out.println(route1);
System.out.println("DONE");
}
};
public static void main(String[] args) {
Example example = new Example();
Thread thread = new Thread(example.rundatapoll);
thread.start();
}
}
Output:
BEFORE THREAD
routeName:I-190 N; Electric Ave,routeDurationInMinutes
AFTER RUNNING THREAD:
I-190 N; Electric Ave
DONE
Or you could use a JSON parser. Something like this:
package example;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonExample {
public static void main(String[] args) {
try {
String json = "{\"routes\":[{\"routeName\":\"I-190 N; Electric Ave\",\"routeDurationInMinutes\":70,\"routeLengthKM\":83.865,\"routeLengthMiles\":52.111278915,\"toll\":false},{\"routeName\":\"I-190 N; Greenville Rd\",\"routeDurationInMinutes\":82,\"routeLengthKM\":92.569,\"routeLengthMiles\":57.519692099000004,\"toll\":false}],\"startPoint\":\"street address\",\"endPoint\":\"destination\",\"startLatitude\":\"42.20115054203528\",\"startLongitude\":\"-71.85038140607858\",\"endLatitude\":\"42.201220801535\",\"endLongitude\":\"-71.849075146695\"}";
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(json);
JSONArray routes = (JSONArray) obj.get("routes");
System.out.println("ROUTES: ");
for(Object route : routes) {
JSONObject routeObj = (JSONObject) route;
String routeName = routeObj.get("routeName") + "";
System.out.println("Route name: " + routeName);
}
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
Output:
ROUTES:
Route name: I-190 N; Electric Ave
Route name: I-190 N; Greenville Rd