103 lines
1.9 KiB
Java
103 lines
1.9 KiB
Java
package edu.grcc;
|
|
|
|
import java.util.Scanner;
|
|
import java.io.FileInputStream;
|
|
import java.io.IOException;
|
|
|
|
public class Main {
|
|
public static void main(String[] args) {
|
|
// Create tasks
|
|
// Only need one task. One that prints current line.
|
|
Runnable printA = new PrintFile("FileA.txt");
|
|
Runnable printB = new PrintFile("FileB.txt");
|
|
Runnable print100 = new PrintFileNumbers("File100.txt");
|
|
|
|
//Create threads
|
|
Thread thread1 = new Thread(printA);
|
|
Thread thread2 = new Thread(printB);
|
|
Thread thread3 = new Thread(print100);
|
|
|
|
// Start threads
|
|
thread1.start();
|
|
thread2.start();
|
|
thread3.start();
|
|
}
|
|
}
|
|
|
|
class PrintFile implements Runnable {
|
|
|
|
private String fileToPrint;
|
|
|
|
public PrintFile(String s) {
|
|
fileToPrint = s;
|
|
}
|
|
|
|
@Override /** Override the run() method to tell the system
|
|
* what the task to perform
|
|
*/
|
|
public void run() {
|
|
FileInputStream fileByteStream = null;
|
|
Scanner inFS = null;
|
|
|
|
String s = "";
|
|
|
|
try{
|
|
fileByteStream = new FileInputStream(fileToPrint);
|
|
inFS = new Scanner(fileByteStream);
|
|
|
|
while (inFS.hasNextLine()){
|
|
|
|
s = inFS.nextLine();
|
|
System.out.print(s);
|
|
Thread.yield();
|
|
}
|
|
inFS.close();
|
|
}
|
|
catch(IOException e){
|
|
}
|
|
}
|
|
}
|
|
class PrintFileNumbers implements Runnable {
|
|
private String fileToPrint;
|
|
|
|
public PrintFileNumbers(String s){
|
|
fileToPrint = s;
|
|
}
|
|
|
|
public void run() {
|
|
FileInputStream fileByteStream = null;
|
|
Scanner inFS = null;
|
|
|
|
String s = "";
|
|
|
|
Thread thread4 = new Thread(
|
|
new PrintFile("FileA.txt"));
|
|
thread4.start();
|
|
|
|
try{
|
|
fileByteStream = new FileInputStream(fileToPrint);
|
|
inFS = new Scanner(fileByteStream);
|
|
|
|
while (inFS.hasNextLine()){
|
|
|
|
s = inFS.nextLine();
|
|
System.out.print(s);
|
|
|
|
try{
|
|
if (Integer.parseInt(s) >= 35) Thread.sleep(100);
|
|
if (Integer.parseInt(s) == 50){
|
|
System.out.println("\n Joining thread!");
|
|
thread4.join();
|
|
}
|
|
}
|
|
catch(Exception e){
|
|
}
|
|
|
|
}
|
|
inFS.close();
|
|
}
|
|
catch(IOException e){
|
|
}
|
|
}
|
|
}
|