1. Write a program to define three threads with NORMAL, LOW and HIGH priority.
Run all three
threads to demonstrate the Thread Priority concept..
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " with priority " +
Thread.currentThread().getPriority() + " is running");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class ThreadPriorityExample {
public static void main(String[] args) {
// Creating threads
MyThread thread1 = new MyThread("Thread-1 (Low Priority)");
MyThread thread2 = new MyThread("Thread-2 (Normal Priority)");
MyThread thread3 = new MyThread("Thread-3 (High Priority)");
// Setting priorities
thread1.setPriority(Thread.MIN_PRIORITY); // Low priority
thread2.setPriority(Thread.NORM_PRIORITY); // Normal priority
thread3.setPriority(Thread.MAX_PRIORITY); // High priority
// Starting threads
thread1.start();
thread2.start();
thread3.start();
}
}
OutPut:
2.Write a Java program to check whether the fi le is readable, writable and hidden.
import java.io.File;
public class FileAttributesCheck {
public static void main(String[] args) {
String filePath = "example.txt";
File file = new File(filePath);
if (file.exists()) {
// Check if the file is readable
if (file.canRead()) {
System.out.println("The file is readable.");
} else {
System.out.println("The file is not readable.");
}
if (file.canWrite()) {
System.out.println("The file is writable.");
} else {
System.out.println("The file is not writable.");
}
if (file.isHidden()) {
System.out.println("The file is hidden.");
} else {
System.out.println("The file is not hidden.");
}
} else {
System.out.println("The file does not exist.");
}
}
}
OutPut:
3.Write a program that will count the number of characters and words in a file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileWordCharacterCount {
public static void main(String[] args) {
String filePath = "example.txt";
int wordCount = 0;
int characterCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
characterCount += line.length();
String[] words = line.split("\\s+");
wordCount += words.length;
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
System.out.println("Number of characters: " + characterCount);
System.out.println("Number of words: " + wordCount);
}
}