I have such problem: program should read information from console in separate thread, and when l want to close this thread - input remains active. How to close input after interrupting thread? (programm runs at Eclipse IDE)
public static void main(final String[] args) {
for (int i = 0; i < 10; i++){
ChatRunner.reader = new BufferedReader(
new InputStreamReader(System.in, ChatRunner.charset));
//some treatment
final Thread input = new Thread(() -> {
try {
ChatRunner.answerFromConsole = ChatRunner.reader.readLine();
} catch (final IOException ioe) {
//
}
});
input.start();
// some treatment
input.interrupt();
}
}
If l simply close BufferedReader, i can't use it in next step in loop.
Related
I am trying to parallel execute my code, but got now a problem.
The code without parallel execution is waiting for input (1) and then he is printing out something (2).
Now I execute my code parallel with the help of a timer (task2) and for the input (1)I got another loop.
Now if I try to write something down but I am not fast enough, the input isn't reading the whole input which was interrupted by the task2 with the print out.
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintStream out = new PrintStream(System.out);
static void test1(BufferedReader in, PrintStream out) throws IOException {
String input = in.readLine();
if (input.equals("test"))
System.out.println("true input");
else System.out.println("false input");
}
public static void main(String[] args) throws IOException {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
while (true) {
System.out.println("print");
Thread.sleep(1000);}}}, 1000);
while (true)
test1(in, out);
}
https://imgur.com/iyIdWeA
You could read single characters until you press Enter.
StringBuilder strBuilder = new StringBuilder();
char ch;
while((ch = in.read()) != '\n'){
strBuilder.append(ch);
}
String input = strBuilder.toString();
I've been thinking about this for a few days now, and I am under the belief that my thinking of how multithreading works is flawed. I've consulted the API for Concurrency, and still did not get an answer to my question.
If I have some process that I want to return a unique string, and I want 100 different threads to run this process (thereby giving me 100 threads with 100 different strings), I can utilize executorServices to accomplish this, correct?
Then, once every thread has a string, I want to send that string to a queue, thereby blasting the queue with messages (again, sounds like a usage for a executorService.submit() call).
Lastly, Once a thread sends the message to to the queue, I want this thread to immediately start checking another queue for a response (matching it's unique string), and if it matches, output some data and terminte.
Although I am under the impression that using Executorservice would be the answer to my issue, I am failing in implementation. Is there another solution that I am missing, or does multithreading using using this method suffice--and if so, how?
Code thus far. I stopped after the sendTextMessage after realizing my issue:
int arraySize = 750; //Number of hits to send out: MANIPULATE THIS IF YOU WANT TO SEND MORE
// String[] toSend = new String[arraySize];
String[] rfids = new String[arraySize];
double total = 0;
int count = 0;
//Insert Connection information and set up clients here//
clientSend.connectSend();
clientRec.connectRec(); //edit to ensure credientials are corrects
// System.out.println("Signed-in");
StringBuffer output = new StringBuffer(); //What holds out output
File infile = new File("infile.txt"); //Populating Rfids array
Scanner scan = new Scanner(infile);
for (int i = 0; i <= arraySize-1; i++)
{
if(scan.hasNextLine())
{
rfids[i]=scan.nextLine();
// System.out.println(rfids[i]);
}
}
scan.close();
count=0;
ExecutorService load = Executors.newFixedThreadPool(arraySize);
Callable<String> readAndSendPrep = () ->
{
StringBuffer fileBasedResponse = new StringBuffer();
String rfid = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("input.txt")); //This is the standard message that will be sent everytime, give or take
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line; //temp var
for(int x = 0; x<arraySize-1;x++)
{
try {
while ((line = reader.readLine ()) != null)
{
if (line.trim().startsWith("<MessageId>"))
{
// System.out.println(rf);
rfid = rfids[arraySize]; //not necessary i think
int endIndex = line.trim().indexOf("</MessageId>");
String messageId = line.trim().substring(11, endIndex);
line = "<MessageId>" + messageId + " - " + rfids[arraySize] + "</MessageId>"; //puts unique ID in thread details
}
else if (line.trim().startsWith("str"))
{
// System.out.println(allRFID[thisIndex]);
rfid = rfids[arraySize];
line = "str" + rfids[arraySize] + "str"; //Another unique ID
// System.out.println("BOOM");
}
fileBasedResponse.append(line); //put the whole response to the StringBuffer object
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thread.sleep(1);
return fileBasedResponse.toString();
};
TimeUnit.SECONDS.sleep(10);
Future<String> fileBasedResponse = load.submit(readAndSendPrep);
while(!fileBasedResponse.isDone())
{
Thread.sleep(1);
}
String fileBasedResponseStr = fileBasedResponse.toString();
Runnable sender = () ->
{
try {
clientSend.sendTextMessage(fileBasedResponseStr);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
clientSend.close(); //close connections
clientRec.close();
System.out.println(output.toString()); //output the results
System.out.println(count);
I am very much new to java programming.I need to read a huge java file in smaller chunks. For example
if I have the file as follows
a
b
c
d
e
f
g
h
I have the batch size as 2. As per the above file I need to create 4 batches and then process. I dont need to have a multi threading mode in this task.
Following is what I have tried. I know it is simple and I have come closer to what i want to acheive.
Any suggestions on the code will be helpful
public class testing {
public static void main(String[] args) throws IOException {
System.out.println("This is for testing");
FileReader fr = null;
try {
fr = new FileReader("C:\\Users\\me\\Desktop\\Files.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int batchSize=2;
int batchCount=0;
int lineIncr=0;
BufferedReader bfr = new BufferedReader(fr);
String line;
int nextBatch=0;
int i=0;
while((line=bfr.readLine())!= null) {
if (lineIncr <=nextBatch ) {
System.out.println(line);
int b=0;
i=i+1;
if (i==2) {
b=b+1;
System.out.println("batchSize : "+b);
System.out.println("batchSize : "+b);
}
}
}
bfr.close();
}
}
Try this:
final int batchSize = 2;
Path file = Paths.get("C:\\Users\\me\\Desktop\\Files.txt");
try (BufferedReader bfr = Files.newBufferedReader(file)) {
List<String> batch = new ArrayList<>(batchSize);
for (String line; (line = bfr.readLine()) != null; ) {
batch.add(line);
if (batch.size() == batchSize) {
process(batch);
batch = new ArrayList<>(batchSize); // or: batch.clear()
}
}
if (! batch.isEmpty()) {
process(batch);
}
}
Notable features:
Uses new NIO 2 Path API, instead of old File API.
Uses try-with-resources to ensure Reader is always closed correctly.
Collects the batch of lines in a List<String>.
Calls process(List<String> batch) method to do the processing.
Call process() with partial batch, if last batch is incomplete.
I have problem. I need to create 9 files, each called from thread name. Each file will be called 1.txt, 2.txt, 3.txt etc. Each file will be filled with a symbol that corresponds to the name of the file (1.txt file is "1"). Each file should be 100 lines, each line length is 100 characters. This work must perform threads of execution and I\O. I need to read the contents of these files in the resulting file super.txt, when using several threads.
My code:
public class CustomThread extends Thread {
Thread t;
String threadName;
CustomThread(String threadName) {
this.threadName = threadName;
}
#Override
public void run() {
if (t == null) {
t = new Thread(this);
}
add(threadName);
}
public void add(String threadName) {
File f = new File(threadName + ".txt");
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("File does not exists!");
}
}
FileWriter fw = null;
try {
fw = new FileWriter(f);
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
fw.write(threadName);
}
fw.write('\n');
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("File does not exists!");
}
}
}
My main:
public class Main {
public static void main(String[] args) {
CustomThread T1 = new CustomThread("1");
T1.start();
CustomThread T2 = new CustomThread("2");
T2.start();
}
}
First question. I need, to make threads in cycle. Look on my main: I create
CustomThread T1 = new CustomThread("1");
T1.start();
But, i want to create 9 files in cycle. How to do this ?
Second question. I need to write in every my file from multiple threads.
Third question. How to write from multiple threads in result file five contents of thats files ?
i want to create 9 files in cycle. How to do this ?
Use a loop
for (int i = 1; i <= 9; i++) {
new CustomThread("" + i).start();
}
I need to write in every my file from multiple threads.
How do you do this? Open the files before you start the threads and lock them when ever you use them.
How to write from multiple threads in result file five contents of thats files ?
Can you rephrase that question?
Using the readLine() method of BufferedReader, can you print the first N lines of a stream in reverse order without using a list or an array?
I think you can do it through recursion with something like:
void printReversed(int n)
{
String line = reader.readLine();
if (n > 0)
printReversed(n-1);
System.out.println(line);
}
How about recursion to reverse the order?
Pseudo code:
reverse(int linesLeft)
if (linesLeft == 0)
return;
String line = readLine();
reverse(linesLeft - 1);
System.out.println(line);
Nice question. Here you have one solution based on coordinated threads. Although it's heavy on resources (1 thread/line of the buffer) it solves your problem within the given constrains. I'm curious to see other solutions.
public class ReversedBufferPrinter {
class Worker implements Runnable {
private final CountDownLatch trigger;
private final CountDownLatch release;
private final String line;
Worker(String line, CountDownLatch release) {
this.trigger = new CountDownLatch(1);
this.release = release;
this.line = line;
}
public CountDownLatch getTriggerLatch() {
return trigger;
}
public void run() {
try {
trigger.await();
} catch (InterruptedException ex) { } // handle
work();
release.countDown();
}
void work() {
System.out.println(line);
}
}
public void reversePrint(BufferedReader reader, int lines) throws IOException {
CountDownLatch initialLatch = new CountDownLatch(1);
CountDownLatch triggerLatch = initialLatch;
int count=0;
String line;
while (count++<lines && (line = reader.readLine())!=null) {
Worker worker = new Worker(line, triggerLatch);
triggerLatch = worker.getTriggerLatch();
new Thread(worker).start();
}
triggerLatch.countDown();
try {
initialLatch.await();
} catch (InterruptedException iex) {
// handle
}
}
public static void main(String [] params) throws Exception {
if (params.length<2) {
System.out.println("usage: ReversedBufferPrinter <file to reverse> <#lines>");
}
String filename = params[0];
int lines = Integer.parseInt(params[1]);
File file = new File(filename);
BufferedReader reader = new BufferedReader(new FileReader(file));
ReversedBufferPrinter printer = new ReversedBufferPrinter();
printer.reversePrint(reader, lines);
}
}
Here you have another alternative, based on BufferedReader & StringBuilder manipulations. More manageable in terms of computer resources needed.
public void reversePrint(BufferedReader bufReader, int lines) throws IOException {
BufferedReader resultBufferReader = null;
{
String line;
StringBuilder sb = new StringBuilder();
int count = 0;
while (count++<lines && (line = bufReader.readLine())!=null) {
sb.append('\n'); // restore new line marker for BufferedReader to consume.
sb.append(new StringBuilder(line).reverse());
}
resultBufferReader = new BufferedReader(new StringReader(sb.reverse().toString()));
}
{
String line;
while ((line = resultBufferReader.readLine())!=null) {
System.out.println(line);
}
}
}
it will also require implicit data structures, but you can spawn threads, run them inorder, and make each thread read a line and wait a decreasing amount of time. the result will be: the last thread will run first, and the first one will run last, each one printing its line. (the interval between them will have to be large enough to ensure large "safety margins")
I have no idea how, if any, that can be done with no explicit/implicit data storage.
Prepend each line you read to a string, and print the string. If you run out of lines to read, you just print what you have.
Alternatively, if you are certain of the number of lines you have, and you do not wish to use a string:
void printReversed(int n, BufferedReader reader)
{
LineNumberReader lineReader = new LineNumberReader(reader);
while (--i >= 0)
{
lineReader.setLineNumber(i);
System.out.println(lineReader.readLine());
}
}