Thứ Bảy, 27 tháng 9, 2014

Thread Demo

question:

There are three threads in a process. The first thread prints 1 1 1 …, the second one prints 2 2
2 …, and the third one prints 3 3 3 … endlessly. How do you schedule these three threads in order to print 1 2 3 1 2 3 …?

solution:

package com.shashi;

class ThreadDemo1 extends Thread
{
   
private int val;
public ThreadDemo1(int val)
{
    this.val=val;
    start();
}
public void run()
{
    while(true)
    {
        synchronized(this)
        {
        try
        {
            wait();
        }
        catch(Exception e)
            {System.out.print(e.getLocalizedMessage());}
            System.out.print(val+" ");
        }
    }
}
   
}

public class ThreadDemo
{
    public static void main(String []args)
    {
        ThreadDemo1 arr[]=new ThreadDemo1[3];
        for(int i=0;i<3;i++)
        {
            arr[i]=new ThreadDemo1(i+1);
        }
        int index=0;
        while(true)
        {
            synchronized(arr[index])
            {
                arr[index].notify();
            }
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception e){System.out.print(e.getLocalizedMessage());}
            index=(++index)%3;
        }
    }
}



output:

------------------------------
1 2 3 1 2 3 1 2 3 1 2 3 .................so on!!!!!
------------------------------


Explanation:

1.first create three threads ,here i created array of three threads.
2.now in order to print format like 1 2 3 1 2 3 ...........,you have to create locks .Here i created locks by using synchronized block.

logic:

if(any thread is avilable)
call wait();
repeat above step;
//next step is to wake up your thread
call notify();

 


Không có nhận xét nào:

Đăng nhận xét