Latest News

Showing posts with label multithreading. Show all posts
Showing posts with label multithreading. Show all posts

Thursday, September 29, 2016

September 29, 2016

How to create thread in java?

We can create thread by two methods:
       1.By extends
       2.By implements.

 Example:

class ByExtends extends Thread{ 
public void run()
    {
        System.out.println("thread is running...");
    }
public static void main(String args[]){ 
    ByExtends t1=new ByExtends(); //Create object of ByExtends class
    t1.start();  //start thread
 } 
}


Example:


public class ByImplements implements Runnable {

   
    public void run(){ 
        System.out.println("thread is running..."); 
        } 
         
        public static void main(String args[]){ 
        ByImplements m1=new ByImplements(); 
        Thread t1 =new Thread(m1); //passing class object in thread
        t1.start();  //start thread
         } 
        }


Multiple Thread:

Example:

public class MultipleThread implements Runnable{
   
    public void run(){
        System.out.println("The current Thread = "+Thread.currentThread().getName());
    }
     
}
 class Multithread{
    public static void main(String[] args) {
        MultipleThread mThread=new MultipleThread();
        Thread t1=new Thread(mThread);
        Thread t2=new Thread(mThread);
        Thread t3=new Thread(mThread);
        t1.start();
        t2.start();
        t3.start();
       
    }
}

September 29, 2016

Thread Priroty in java.

Thread Priority:

  1. public static int MIN_PRIORITY=1
  2. public static int NORM_PRIORITY=5
  3. public static int MAX_PRIORITY=10

Example:

 class Test implements Runnable{
    public void run(){
        System.out.println("Priority of current thread="+Thread.currentThread().getPriority());
   //getting default priority
    }
  
}
public class GetPriorityDemo{
    public static void main(String[] args) {
        Test t=new Test();
        Thread t1=new Thread(t);
        t1.start();
    }
}


Set Priority in java: 

class Test1 implements Runnable{
    public void run(){
        System.out.println("Priority of current thread="+Thread.currentThread().getPriority());
    }
   
}
public class SetPriorityDemo{
    public static void main(String[] args) {
        Test t=new Test();
        Thread t1=new Thread(t);
        t1.setPriority(4);//set priority
        t1.start();
        //Thread.yield();
    }
}
September 29, 2016

How to read .txt file in java?


To read the file you can use buffered reader class.



Example:


public class ReadFromBufferReader {

     public static void main(String[] args) throws IOException
 {

   File fl = new File("d:/myfile.txt");//path of your text file

   BufferedReader br = new BufferedReader(new FileReader(fl)) ;
   String str;
   while ((str=br.readLine())!=null)
   {
    System.out.println(str);
   }
   br.close();

  }


}