Recently I've started to learn Java and I have a question about IO streams and threads. In our language, both of the definitions translate like "Поток" and it confuses me.
I'm wondering about conception in general for both topics: streams and threads. I will provide an example that will show my point of view related to this topic.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try{
FileOutputStream fos = new FileOutputStream("C:\\Users\\TMS\\Desktop\\Workspace\\src\\File.txt");
FileInputStream fis = new FileInputStream("C:\\Users\\TMS\\Desktop\\Workspace\\src\\FileWithInfo");
int supnum = 0;
try{
while((supnum = fis.read()) != -1){
fos.write(supnum);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
As I can understand I created instances of two classes: FileOutputStream and FileInputStream. Instances of these classes we can use as a "controller" which helps us to control our streams by providing with the methods (.write and .read for example) and at the same time implicitly Java "speaks" with the processor and tells the processor to create new streams (I'm not sure, but probably if we create lots of streams, we even will see them in Task Manager).
So in the and we have a chain:
- instance of the class that will help us to control our stream.
- our stream which we use for transferring data.
- our file, that we use (for reading or writing information).
And if we talk about threads the chain is almost the same:
public class Program {
public static void main(String[] args) {
System.out.println("Main thread started...");
Runnable r = ()->{
System.out.printf("%s started... \n", Thread.currentThread().getName());
try{
Thread.sleep(500);
}
catch(InterruptedException e){
System.out.println("Thread has been interrupted");
}
System.out.printf("%s finished... \n", Thread.currentThread().getName());
};
Thread myThread = new Thread(r,"MyThread");
myThread.start();
System.out.println("Main thread finished...");
}
}
We have an instance (myThread), which helps us to control our thread with the methods.
The difference that I see is that streams can use only for transferring data but threads are a more complex tool, which allows us to use them as an additional .main(String[] args) method.
I want to know:
Is my guesses correct?
- If not, what is the difference between these terms?
Why IO related classes don't implement Runnable interfaces like class Thread?
Can we use threads for transferring data like we use streams?