I am trying this program in java but I am not getting any output when I put everything in the run() method
Main.java:
public class Main {
static int line;
static boolean ret = true;
static BufferedReader br;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File f = new File("tere.dat");
// boolean ret = f.createNewFile() ;
br = new BufferedReader(new FileReader(f));
new Test(br.readLine());
new Test(br.readLine());
}
}
Test.java:
public class Test extends Thread {
private String input;
static int thread_count = 0;
public Test(String l)
{
input = l;
}
public void run()
{
System.out.println("Checking from other class : This was printed from file :>>");
System.out.println(input);
String upper = input.toUpperCase();
System.out.println("");
System.out.println("The String in all UpperCase :" + upper);
}
}
What I want to do is that I want to read lines from a file using two threads and then display whatever I get . I am new to Java
EDIT :
I was not using the start() method. Though even after using start() It reads only 2 lines from the file and stops. What could be the problem
?
You have to start() your Threads.
Also, i would suggest reading a good tutorial on Threads and concurrency in Java before proceeding, as it's a complex subject.
You need to start your thread with start() I suggest you not extend Thread but instead implement Runnable.
BTW: Unless you type impossibly fast, you won't see the difference in using threads. It will take about 0.1 milli-seconds to start the thread and finish it so unless you type much faster than that, it will make no difference.
You need to start threads:
(new Test(br.readLine())).start();
And also, you have to add some join to wait threads to finish because your main thread will finish execution before created threads.
You have to start them:
(new Test(br.readLine())).start();
(new Test(br.readLine())).start();
Related
I don't know how to print to a text file when I'm using threads because every time it just creates another file, so I end up with just one result which is the last one, I have tried a lot of things and is always the same.
This is just a part of the code, besides printing to the file I have to print a graph too and I have the same problem as it creates one graph for each thread.
public class Adsda implements Runnable{
private int id=0;
public int number;
public String file="Time.txt";
private final PrintWriter outputStream;
public Adsda(int id) throws FileNotFoundException {
this.id=id+1;
this.outputStream=new PrintWriter(this.file);
}
public void run() {
int i,fact=1;
this.number=id;//It is the number to calculate factorial
long A=System.nanoTime();
for(i=1;i<=this.number;i++){
fact=fact*i;
}
long B=System.nanoTime();
long t=B-A;
double tt = (double)t / 1000000000.0;
System.out.println("Factorial of "+number+" is: "+fact+" Time: "+tt);
this.outputStream.println("Factorial of: "+this.number+" Time: "+tt);
this.outputStream.flush();
}
public static void main(String[] args) throws FileNotFoundException{
ExecutorService executor = Executors.newFixedThreadPool(2);//creating a pool of 2 threads
for(int i=0;i<5;i++){
executor.submit(new Adsda(i) );
}
executor.shutdown();
}
You should create a single PrintWriter and share that with the threads by passing it in the constructor instead of having each thread create their own PrintWriter (and file). Although that will result in the file containing the results in weird order. If you want to have them in a specific order, you should have the threads output their results in their own buffers and when all threads are finished, write the buffers out to a file in sequence.
PrintWriter pw = new PrintWriter(filename);
for(int i=0;i<5;i++){
executor.submit(new Adsda(i, pw) );
}
Just to answer your question, you have multiple threads that execute your run method and all of them will write the file named "Time.txt". You should write a file for each thread. Also you are sharing your output stream between multiple threads which is an issue in itself. Move the print writer creation in the run method and use a name like "time" + Thread.curentThread().getID() + ".txt". That should fix it.
I am writing java program that creates different instances of Runnable objects given by someone and then runs them. For instance user gives me a .class file with runnable class and I create instance of that object and run it. Everything works fine until I decided to monitor every different thread's progress. Lets say that current Runnable object print all the numbers from 1 to 9 in console. I want to catch that output and return it as a String. Using System.setOut(..) prevents me from using console, so it is not an option.
Using setOut doesn't prevent you from using the console, if you save it first and it is your only option unless you use byte code instrumentation.
static final PrintStream OUT = System.out;
static {
// capture all System.out
System.setOut(new MyPrintStream());
OUT.println("Print as normal");
}
class MyPrintStream extends PrintStream {
final ThreadLocal<StringBuilder> text = ThreadLocal.withInitial(() _> new StringBuilder());
public void print(String s) {
StringBuilder sb = text.get();
sb.append(s);
}
public void println(String s) {
StringBuilder sb = text.get();
sb.append(s).append('\n');
// do something with sb.
}
Below is my code to extract text from a text file and displaying it on the console.
Could some one please tell me how to make this program run on multiple threads simultaneoulsly?
I would also like to know if multiple threads are being used in performing the task as the time taken to run the task is varied every time i run.??
//Code
import java.io.*;
import java.util.*;
class Extract{
static int i=0;
FileInputStream in;
BufferedReader br;
ArrayList<String> stringList;
String li;
Extract() throws FileNotFoundException
{
FileInputStream in = new FileInputStream("C:\\Users\\sputta\\workspace\\Sample\\src\\threads.txt");
br = new BufferedReader(new InputStreamReader(in));
stringList = new ArrayList<String>();
li=" ";
}
void call()
{
try{
while(li!=null)
{
String str = br.readLine();
stringList.add(str);
li=stringList.get(i);
if(li!=null)
{
System.out.println(li);
i++;
}
}
Thread.sleep(1000);
in.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Caller implements Runnable {
Extract target;
Thread t;
public Caller(Extract targ)
{
target = targ;
t = new Thread(this);
t.start();
System.out.println(t.isAlive());
}
public void run()
{
synchronized(target) { // synchronized block
target.call();
}
}
}
public class Sample {
public static void main(String args[]) throws FileNotFoundException
{
long startTime = System.currentTimeMillis();
System.out.println(startTime);
Extract target = new Extract();
Caller ob1 = new Caller(target);
Caller ob2 = new Caller(target);
Caller ob3 = new Caller(target);
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
It does not make much sense performance-wise to have multiple threads reading from the same file, due to the inevitable input/output (I/O) bottleneck.
Two things that can be done to improve the situation:
"Split" the file into smaller pieces and assign each such "split" to a different thread. This is the approach followed by Hadoop, but it does require copying each "split" before processing, so it is only beneficial for large files (say, at least 100 MB each, or much more).
Use 1 thread to read from the file into a "prefetch" buffer, in memory, and then process the input from the buffer, via multiple other threads. A variation of this approach would be for the prefetch thread to "feed" each of the "consumer" threads with data, before each of them starts. Obviously, the relative allocation of prefetch vs. processing across the threads, will yield varying results, so further tuning would be necessary, depending on the application.
Both approaches have limitations and do not guarantee performance improvements in all cases.
Reading a text file line-by-line from a single thread can be done at a speed of over 1 million lines/sec, but still the bottleneck will remain in I/O, as already discussed.
I posted yesterday about this but my code was messy. What I'm looking to do is count the number of lines of two separate files and print the line number in a separate thread for each file.
This is what i have:
import java.io.File;
import java.util.Scanner;
public class fileReader implements Runnable
{
static int count = 0;
static int count1 = 0;
public void run()
{
try
{
Scanner file1 = new Scanner(new File("filetest1.txt"));
Scanner file2 = new Scanner(new File("filetest2.txt"));
while (file1.hasNextLine())
{
count++;
file1.nextLine();
}
while (file2.hasNextLine())
{
count1++;
file2.nextLine();
}
}
catch(Exception e)
{
count = -1;
count1 = -1;
}
}
public static void main(String[] args)
{
(new Thread(new fileReader())).start();
System.out.println("File one has " + count + " lines");
System.out.println("File two has " + count1 + " lines");
}
}
The problem is that it does not work. Can someone point me in the right direction? Thanks.
You are on the right track using Runnable. You have a couple problems right now:
You currently create 1 fileReader with 1 thread for both files, but your intent is to have a separate thread for each.
You are trying to communicate between threads using some static variables, but you're not waiting for the worker thread to be done before printing the variables.
To solve your first problem, you need to create a new Runnable and a new thread for each file. (I'm going to rename your fileReader class to LineCounter to avoid confusion with the similarly named FileReader from the standard library).
class LineCounter implements Runnable {
private final File file;
public LineCounter(File file) {
this.file = file;
}
public void run() {
// Count lines in file.
}
}
Now you can create 2 separate LineCounter objects, one to count the lines in each file.
Thread thread1 = new Thread(new LineCounter(new File("filetest1.txt")));
Thread thread2 = new Thread(new LineCounter(new File("filetest2.txt")));
thread1.start();
thread2.start();
As for your second problem, your main thread must (the one that spawned off these two other threads) needs to wait for them to complete before reading the variables holding the number of lines in each file. You can instruct your main thread to wait for the another thread to complete by using join()
thread1.join();
thread2.join();
// Print your variables.
That being said, communicating between threads with static variables is dubious at best:
To really do this right, you'd have to either synchronize access to those variables, or else declare them as volatile.
When programming with threads, it's preferable to share as little state (variables) as possible with other threads.
Further, there exists the very convenient Executor framework which presents a nicer API for dealing with threads. One big win is that is allows you to easily return a value from a thread, which you could use to return the number of lines read.
The big changes are:
Your class implements Callable<Integer> instead of Runnable. The <Integer> part here means you want your thread to return an Integer (i.e. the number of lines in the file)
Instead of void run(), you define Integer call(), which returns the number of lines in the file.
Instead of creating Threads directly, you submit tasks to be done to an Executor.
Instead of join()ing threads together, simply get() the return value of a thread from a Future.
Converted to Executor style, the solution is something like
class LineCounter implements Callable<Integer> {
private final File file;
public LineCounter(File file) {
this.file = file;
}
public Integer call() {
// Count number of lines in file.
return numLines;
}
}
And in your main thread:
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> future1 = executor.submit(new LineCounter(new File("file1.txt")));
Future<Integer> future2 = executor.submit(new LineCounter(new File("file2.txt")));
Integer file1Lines = future1.get();
Integer file2Lines = future2.get();
You need to wait for the thread to finish its job.
You print your resault too early.
thr.join() blocks your program until thr finishes.
public static void main(String args[]) {
try {
Thread thr = new Thread(new fileReader());
thr.start();
thr.join();
System.out.println("File one has " + count + " lines");
System.out.println("File two has " + count1 + " lines");
} catch (InterruptedException ex) {
Logger.getLogger(fileReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
public class fileReader1 implements Runnable
{
static int count = 0;
public void run()
{
try
{
Scanner file1 = new Scanner(new File("filetest1.txt"));
............
............
............
}
}
public class fileReader2 implements Runnable
{
static int count = 0;
public void run()
{
try
{
Scanner file1 = new Scanner(new File("filetest2.txt"));
............
............
............
}
}
Now you can start two threads and start reading the files simultaneously:
Thread t1=new Thread(new fileReader1());
Thread t2=new Thread(new fileReader2());
t1.start();
t2.start();
I have a method which takes a list and do some processing on it and it updates another global list. I need to run multiple instances of this method with different lists input in parallel.
Does multi-threading support this? If yes, how can i use it i.e.: what shall i put in the thread? Examples are highly appreciated.
I am thinking of having a static list in the thread class which gets updated by the different instances of the thread while running (the list contains strings and counters, so the update is adding new strings or increasing the counters of existing ones).. i need to read whatever gets added to this global list every 10 seconds and print it.. is using static list suitable for this and how can i make it thread safe?
Yes, that's a very common usage of multithreaded programming.
class ListProcessor implements Runnable {
/* field/s representing param/s */
public ListProcessor(/* param/s */) {
/* ... */
}
#Override
public void run() {
/* process list */
}
}
Then, when you want to actually process some lists.
class SomeClass {
ExecutorService listProcessor;
public SomeClass(/* ... */) {
listProcessor = ExecutorService.newFixedThreadPool(numThreads);
/* for each thread, however you want to do it */
listProcessor.execute(new ListProcessor(/* param/s */));
/* when finished adding threads */
listProcessor.shutdown();
/* note that the above two lines of code (execute/shutdown) can be
* placed anywhere in the code. I just put them in the constructor to
* facilitate this example.
*/
}
}
#purtip31 has a start for the parallel processing stuff.
I'm concerned about the results - you mention that you update a "global list". If multiple threads at a time are trying to update that list at the same time there could be problems. A couple of options:
Make sure that list is properly thread safe. This may or may not be easy - depends on exactly what is getting changed.
Use ExecutorService, but with the invokeAll() method, which runs a bunch of Callables in parallel and waits till they are all done. Then you can go through all of the results and update them one at a time. No threading issues with the results. This means that your code will have to implement Callable instead of Runnable (not a big deal). I have a blog with an example here
Well Sam...i m not much cleared with your question.....
try this out....
Following is a code which would help u to run mulitple instances.......
Main thread
public class mainprocess
{
public static LinkedList globallist;
public static String str;
public int num;
public static void main(String Data[])
{
globallist = new LinkedList();
// LinkedList will be passed as pass by reference.....
// globalist is made static and assigned likewise for global use..
childprocess.assignlist(globallist);
childprocess p1 = new childprocess("string input"); // a string input...
childprocess p2 = new childprocess(number input); // a number input...
p1.t.join();
p2.t.join();
}
}
The Child Thread.....
public class childprocess implements Runnable
{
public Thread t1,t2;
public boolean inttype,stringtype;
String string;
int num;
public static LinkedList temp = new Linkedlist();
public static assignlist(LinkedList ll)
{
temp = ll;
}
public childprocess(String str)
{
string = str;
t1 = new Thread(this,"stringThread");
t1.start();
}
#override
public childprocess(int n)
{
num = n;
t2 = new Thread(this,"numberThread");
t2.start();
}
#override
public void run()
{
// Both will be executed in a threader manner based on the condition...
if(Thread.currentThread().getName().equals("stringThread")
{
// your process using string......
childprocess.temp.add(str);
}
else if(Thread.currentThread().getName().equals("numberThread")
{
// your process using number.....
chilprocess.temp.add(num);
}
}
}
If you are using functions that should be restricted to only one thread at a time...
include the syntax....
public synchronized func_type func_name()
{
}