Java Practice Exercise – Threads

  • Write a program to demonstrate Thread synchronization (Producer – Consumer Problem)
  • Write a program TestThreadMany.java that takes a positive integer n from the command line and creates exactly n threads that print out their own name. Here is a sample execution:
$ java TestThreadMany 4
Hello, I am Thread #1
Hello, I am Thread #2
Hello, I am Thread #3
Hello, I am Thread #4
  • Write a java program to implement a multi-threaded application that has two threads. First thread generates the Fibonacci series and the second thread generates prime numbers. Create a main program that displays numbers common to both threads.
  • Write a java program that implements a multi-threaded application that has three threads. First thread generates a random integer every 1 second and if the value is even, second thread computes the square of the number and prints. If the value is odd, the third thread will print the value of cube of the number
  • Write a program that runs 5 threads, each thread randomizes a number between 1 and 10. The main thread waits for all the others to finish, calculates the sum of the numbers which were randomized and prints that sum. You will need to implement a Runnable class that randomizes a number and store it in a member field. When all threads have done, your main program can look over all the objects and check the stored values in each object.
  • Write a Java program ‘WordCount’ that counts the words in one or more files. Start a new thread for each file. For example, if you call
“java WordCount  report.txt  address.txt  Homework.java”
then the program might print
address.txt: 1052
Homework.java: 445
report.txt: 2099
  • Write a java program for generating three threads to perform the following operations
    • Getting N numbers as input
    • Printing the numbers divisible by five
    • Computing the average.
  • Write a Java program for generating four threads to perform the following operations:
    • Getting ‘N’ numbers as input
    • Printing the even numbers
    • Printing the odd numbers
    • Computing the average
  • Write a java program to implement a multi-threaded application that has three threads. First thread generates even numbers, second thread generates odd numbers and the third thread generates numbers which are multiples of 5. Create a main program that reads and displays numbers from each thread