I am coding for a program whose detail is: 1. User enter the value in array and in program automatically entered value times 0 should be inserted in each index. 2. Use threads, first thread calls it decrement(2) in the user entered value and then it goes to sleep for 1 second. As sleep calls then second thread calls it put a increment of 1 and then sleep goes for 2 seconds then again first thread call it again decrement in the incremented value and so on until the value of decremented thread equals to zero. As value of decrement equal to zero then incrementing automatically must stop.
I have the code now help me if any one has understand my question...
All comments should be appreciated..
//Through Implementing Runnable Interface
//Create a second thread
//import java.util.Scanner;
class NewThread extends Thread implements Runnable {
Thread t;
NewThread(){
//Create a new, second thread
t = new Thread(this, "Demo AASSINGMENT");
//System.out.println("Child Thread: "+ t);
t.start();//Start the thread
}
//This is the entry point for the second thread.
public void run(){
try{
for(int i = 10; i>0; --i){
System.out.println("Decrement: " +i);
//i--;
//System.out.println("Child Thread 2nd dec: " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("Decrement INterrupted");
}
System.out.println("Oops!! -- Decreasing Value is less than or equal to zero");
}//run
}//class
class ThreadDemo {
public static void main(String args[]){
new NewThread();//create a new thread
int[] arr; int dj;
// Scanner input = new Scanner(System.in);
// System.out.print("Enter Your Desired Value : ");
//int z = input.nextInt();
try{
//arr = new int[z];
//for(dj =0; dj<array.length;dj++)
//{
// array[dj]=0;
// System.out.println("0's inserted "+ array[dj]);
//}
//while(z!=0){
for(int i = 10; i<=14; i++){
System.out.println("Increment: " +i);
//if(i>6){
//System.out.println("Main Thread Exiting");}
Thread.sleep(2000);
}//for
}//try
catch(InterruptedException e){
System.out.println("Main Thread Interrupted");
}
System.out.println("Increasing Value has exceeded from 14 so Exiting");
}//main
}//class
In your main method, you create an instance of newThread
, but you never start it. Unless you start it, it will never execute.
Edit to provide more implementation info
As a precursor to the following explanation, normally you don't have your classes extend Thread
. Instead, implement Runnable
then create a standard Thread
instance that executes your Runnable
instance.
So, I would suggest that you modify the code as follows:
class NewRunnable implements Runnable
{
public void run()
{
// Do important background stuff here
}
}
public static void main (String[] args)
{
Thread thr = new Thread ( new NewRunnable( ) ) ;
thr.start( ) ;
// Do other important stuff
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.