A Simple Multithreaded Program in Java

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

Here I am explaining a simple multi-threaded program.

The main thread writes 5000 to 1 in a file named MainThread.txt and the child thread writes 1 to 5000 in a file named childthread.txt.
Both will happen at the same time. That is it will run in parallel.

We are creating a child thread class by implementing a method Runnable.

This class will contain a method named run() where we do our functionality.

We will instantiate this thread class in the main method, so it will run along with the main thread.

The child thread class is

package com.amal.thread;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ThreadTest implements Runnable {
	Thread t;
	ThreadTest()
	{
		t=new Thread(this,"My Test");
		System.out.println("My test thread");
		t.start();

	}
	public void run() {
		File file=new File("childthread.txt");

		try {

			FileWriter fwt = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bwt = new BufferedWriter(fwt);

			for(int i=0; i<5000; i++)
			{
				bwt.write("thread "+i);
				bwt.newLine();
			}				
			bwt.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}

The main class is

package com.amal.thread;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class MainClass {
	public static void main(String[] args) throws IOException {
		new ThreadTest();
		File file1=new File("MainThread.txt");
		FileWriter fw = new FileWriter(file1.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);

		for (int i=5000;i>1;i--)
		{
			bw.write("main "+i);
			bw.newLine();
		}
		bw.close();
	}
}

Advertisements

About amalgjose
I am an Electrical Engineer by qualification, now I am working as a Software Engineer. I am very much interested in Electrical, Electronics, Mechanical and now in Software fields. I like exploring things in these fields. I like travelling, long drives and very much addicted to music.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: