We've moved! — MindVault360 is now SrcForge. Better design, more content & premium notes.

Visit SrcForge →

MindVault360 has moved!

We've upgraded to SrcForge — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at SrcForge

Saturday, August 31, 2024

Life cycle of a thread

 (Tap the post to see more)


Life cycle of a thread

A thread goes through various stages in its lifecycle.  The following diagram shows the complete life cycle of a thread.

 


Following are the stages of the life cycle −

New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. Thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.

← Back Next →

Labels:

Friday, August 30, 2024

Multithreading


(Tap the post to see more)


Multithreading

         Multithreading is a concept where a program is divided into two or more subprograms, which can be executed at the same time in parallel. This is also known as multithreading.

         A thread is similar to a program that has a single flow of control

        The process of executing multiple threads simultaneously is known as multithreading.

Advantages of Multithreading

  1. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time
  2. It enables programmers to do many things at one time
  3. They can make a long program into many threads and execute them in parallel.

Steps to Create a thread in java

         create a new class that extends Thread, then override the run() method and then to create an instance of that class.

        The run() method is what is executed by the thread after you call start().

         Here is an example of creating a Java Thread subclass:

public class MyClass extends Thread

{

         public void run()

         {

         System.out.println("MyClass running");

         }

}

To create and start the above thread:

MyClass t1 = new MyClass ();

T1.start();

When the run() method executes it will print out the text " MyClass running ".

 

Example program to create three threads and display the strings using multithreading concept

class A extends Thread

{

         public void run()

         {

                 for(int i=1;i<=5;i++)

                          System.out.println(“Welcome to C”);

         }

                

}

 

class B extends Thread

{

         public void run()

         {

                 for(int i=1;i<=5;i++)

                          System.out.println(“Welcome to C++”);

         }

                

}

 

class C extends Thread

{

         public void run()

         {

                 for(int i=1;i<=5;i++)

                          System.out.println(“Welcome to Java”);

         }

                

}

class threaddemo

{

         public static void main(String args[])

         {

                 A a=new A();

                 a.start();

 

                 B b=new B();

                 b.start();

                

                 C c=new C();

                 c.start();

                  

         }

}


Example 02:

package com.java.Multi_threading;


// Class that implements Runnable for creating a thread

class Task1 implements Runnable {

    public void run() {

        for (int i = 1; i <= 5; i++) {

            System.out.println("Task 1 - Counting: " + i);

            try {

                Thread.sleep(500); // Simulating some work with sleep

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

}


// Another class that implements Runnable for creating a thread

class Task2 implements Runnable {

    public void run() {

        for (int i = 1; i <= 5; i++) {

            System.out.println("Task 2 - Counting: " + i);

            try {

                Thread.sleep(500); // Simulating some work with sleep

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

}


// Main class to run the threads

class ThreadDemo {

    public static void main(String[] args) {

        // Creating instances of Runnable classes

        Task1 task1 = new Task1();

        Task2 task2 = new Task2();

        

        // Creating threads from Runnable instances

        Thread thread1 = new Thread(task1);

        Thread thread2 = new Thread(task2);

        

        // Starting the threads

        thread1.start();

        thread2.start();

        

        // Main thread work

        for (int i = 1; i <= 5; i++) {

            System.out.println("Main Thread - Counting: " + i);

            try {

                Thread.sleep(500); // Simulating some work with sleep

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

}

Example 03:


package com.java.Multi_threading;

class Table{

void printTable(int n){//method not synchronized

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

Thread.sleep(400);

}catch(Exception e){System.out.println(e);}

}

}

}

class MyThread1 extends Thread{

Table t;

MyThread1(Table t){

this.t=t;

}

public void run(){

t.printTable(5);

}

}

class MyThread2 extends Thread{

Table t;

MyThread2(Table t){

this.t=t;

}

public void run(){

t.printTable(100);

}

}

class TestSynchronization1{

public static void main(String args[]){

Table obj = new Table();//only one object

MyThread1 t1=new MyThread1(obj);

MyThread2 t2=new MyThread2(obj);

t1.start();

t2.start();

}

}

← Back Next →

Labels:

Sunday, August 25, 2024

I/O FUNCTIONS IN C

 


 

 

 


 

Input/Output (I/O) functions in C are used to perform input and output operations between a program and the user or the system. Some of the commonly used I/O functions in C are:

 

printf(): This function is used to print formatted output to the console or terminal. It takes a format string and a list of arguments, which are used to format the output.

Example 01:

#include <stdio.h>

 

int main() {

   char name[] = "John";

   int age = 25;

   printf("My name is %s and I am %d years old.\n", name, age);

   return 0;

}

 

Output: My name is John and I am 25 years old.

 

scanf(): This function is used to read formatted input from the console or terminal. It takes a format string and a list of pointers to the variables where the input should be stored.

Example 02:

#include <stdio.h>

 

int main() {

   char name[20];

   int age;

   printf("Enter your name and age: ");

   scanf("%s %d", name, &age);

   printf("Your name is %s and you are %d years old.\n", name, age);

   return 0;

}

 

Output:

Enter your name and age: John 25

Your name is John and you are 25 years old.

 

getchar(): This function is used to read a single character from the console or terminal. It waits for the user to press a key and returns the ASCII code of the character.

 

 

Example 03:

#include <stdio.h>

 

int main() {

   char c;

   printf("Enter a character: ");

   c = getchar();

   printf("You entered the character %c, which has ASCII code %d.\n", c, c);

   return 0;

}

 

Output:

Enter a character: A

You entered the character A, which has ASCII code 65.

 

putchar(): This function is used to write a single character to the console or terminal. It takes an ASCII code as an argument and writes the corresponding character.

Example 04:

#include <stdio.h>

 

int main() {

   char c = 'A';

   putchar(c);

   return 0;

}

 

Output: A

 

gets(): This function is used to read a string of characters from the console or terminal. It reads characters from the input until it encounters a newline character or the end of the input.

Example 05:

#include <stdio.h>

 

int main() {

   char name[20];

   printf("Enter your name: ");

   gets(name);

   printf("Your name is %s.\n", name);

   return 0;

}

 

Output:

Enter your name: John

Your name is John.

 

Note: The gets() function is considered unsafe because it can cause a buffer overflow if the input string is longer than the size of the buffer.

It is recommended to use the fgets() function instead.

 File I/O (Input/Output) functions in C are used to perform input and output operations on files. There are three main steps involved in file I/O:

 Open the file: In order to perform input and output operations on a file, you need to first open the file. The fopen() function is used to open a file and returns a pointer to a FILE structure.

 Example 06::

#include <stdio.h>

 

int main() {

   FILE *fp;

   fp = fopen("file.txt", "w");

   fprintf(fp, "This is some text in the file.\n");

   fclose(fp);

   return 0;

}

In this example, the file "file.txt" is opened in write mode ("w") using the fopen() function. The fprintf() function is then used to write some text to the file. Finally, the fclose() function is used to close the file.

 

Perform input/output operations: Once the file is opened, you can perform input/output operations on the file using functions such as fgetc(), fgets(), fputc(), fputs(), fprintf(), and fscanf().

Example 07:

#include <stdio.h>

 

int main() {

   FILE *fp;

   char buffer[20];

   fp = fopen("file.txt", "r");

   fgets(buffer, 20, fp);

   printf("The text in the file is: %s\n", buffer);

   fclose(fp);

   return 0;

}

 

In this example, the file "file.txt" is opened in read mode ("r") using the fopen() function. The fgets() function is then used to read a line of text from the file into the buffer. Finally, the printf() function is used to print the text that was read from the file.

 

Close the file: Once you have finished performing input/output operations on the file, you should close the file using the fclose() function.

Example 08:

#include <stdio.h>

 

int main() {

   FILE *fp;

   fp = fopen("file.txt", "a");

   fprintf(fp, "This text is appended to the file.\n");

   fclose(fp);

   return 0;  }

In this example, the file "file.txt" is opened in append mode ("a") using the fopen() function. The fprintf() function is then used to append some text to the end of the file. Finally, the fclose() function is used to close the file.

 

Note: It is important to check whether the file was opened successfully before performing input/output operations on the file. The fopen() function returns NULL if it is unable to open the file, for example if the file does not exist or if the user does not have permission to access the file.

← Back Next →

Labels: