Java Notes: Multithreading & I/O Streams
Multithreaded Programming in Java
Multithreading allows a program to execute multiple tasks simultaneously. A thread is a lightweight
process that runs independently. It improves CPU utilization and performance.
Thread Class
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
}
public static void main(String args[]) {
MyThread t = new MyThread();
[Link]();
}
}
Runnable Interface
class MyClass implements Runnable {
public void run() {
[Link]("Thread using Runnable interface");
}
public static void main(String args[]) {
MyClass obj = new MyClass();
Thread t = new Thread(obj);
[Link]();
}
}
Synchronization
class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}
Deadlock Example
class A {}
class B {}
class Test {
A a = new A();
B b = new B();
void method1() {
synchronized(a) {
synchronized(b) {
[Link]("Thread 1");
}
}
}
}
I/O Streams in Java
Java uses streams to perform input and output operations. A stream represents a flow of data between a
program and a source or destination.
Stream Concept
Input Device → Input Stream → Program → Output Stream → Output Device
File Reading Example
import [Link].*;
class Test {
public static void main(String args[]) throws Exception {
FileInputStream fin = new FileInputStream("[Link]");
int i;
while((i = [Link]()) != -1) {
[Link]((char)i);
}
[Link]();
}
}
Console Input Example
import [Link];
Scanner sc = new Scanner([Link]);
[Link]("Enter your name:");
String name = [Link]();
[Link]("Hello " + name);