Advertisements

How to develop a background function in Python ?

This is an example of executing a function in the background. I was searching for an option to run a function in background along with the normal execution flow.


The main execution will continue in the same flow without waiting for the background function to complete and the function set for background execution will continue its execution in the background.


You can modify this code based on your requirement. Just replace the logic inside function under the @background annotation. Hope this tip helps 🙂


Advertisements

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();
	}
}