error while using isALive() or join method - java

I'm trying to use isALive and join method but its throwing an error like can not find symbol....please tell me where is the error exactly in this program.
and what is the use of join method.i know that it is a wait for threads to finish but i want in details.
class newthread1 implements Runnable {
newthread1() {
Thread t = new Thread(this, "FirstThread");
System.out.println("Child Thread:" + t);
t.start();
}
public void run() {
System.out.println("We are in processing for 1st thread");
int p = 1000, t = 3;
double r = 3.5, si;
try {
si = (p * r * t) / 100;
System.out.println("Simple Interest:" + si);
} catch (ArithmeticException e) {
System.out.println("Error:" + e);
}
}
}
class newthread2 implements Runnable {
newthread2() {
Thread t = new Thread(this, "SecondThread");
System.out.println("Child Thread:" + t);
t.start();
}
public void run() {
try {
System.out.println("We are in processing for 2nd thread");
double a, r = 4.3;
int p = 1000, n = 3;
double temp = Math.pow((1 + r / 100), n);
a = temp * p;
System.out.println("Compound interest:" + a);
} catch (ArithmeticException e) {
System.out.println("Error:" + e);
}
}
}
class mainthread {
public static void main(String args[]) {
newthread1 t11 = new newthread1();
new newthread2();
boolean b = t1.t.isAlive();
System.out.println("Thread is alive:" + b);
t1.t.join();
}
}

Solution 1
Change your main method as
class mainthread {
public static void main(final String args[]) throws InterruptedException {
Thread thread = new Thread(new newthread1());
newthread1 t11 = new newthread1();
new newthread2();
boolean b = thread.isAlive();
System.out.println("Thread is alive:" + b);
thread.join();
}
}
and to run a thread call thread.start(), creating an instnace of an runnable object will not automatically start running. You explicitly tell thread to start or stop.
Solution 2
or you can create Thread object 't' as global varibable and change class as
class newthread1 implements Runnable {
public Thread t;
newthread1() {
t = new Thread(this, "FirstThread");
System.out.println("Child Thread:" + t);
t.start();
}
#Override
public void run() {
System.out.println("We are in processing for 1st thread");
int p = 1000, t = 3;
double r = 3.5, si;
try {
si = p * r * t / 100;
System.out.println("Simple Interest:" + si);
} catch (ArithmeticException e) {
System.out.println("Error:" + e);
}
}
public Thread getT() {
return t;
}
}
and then main method as
class mainthread {
public static void main(final String args[]) throws InterruptedException {
newthread1 t11 = new newthread1();
new newthread2();
boolean b = t11.t.isAlive();
System.out.println("Thread is alive:" + b);
t11.t.join();
}
}

I personally advice you to first take a tutorial regarding basics of Java. I was convinced that you are not clear about basic Java from the following:
boolean b=t1.t.isAlive();
You don't have a varibale named defined as t1 and still you try to use it.
The compiler won't find any variable named t1 and it will complain Cannot find symbol t1
I think you wanted to use t11.
Also even if you use t11 it will still complain because you don't have t as a class variable in your class newthread1, instead you have defined a local variable inside the constructor
Also try to read some java standards like how to declare a class, naming conventions, etc.
It will help you a lot in future.

First error , You have defined the reference variable as t11 :
newthread1 t11=new newthread1();
Hence use t11 in your code:
boolean b=t11.t.isAlive(); // change t1 to t11
Secondly , there is no Thread t instance variable defined in newthread1 or newthread2 classes. This might help :
class newthread1 implements Runnable{
Thread t; // make this an instance variable , currently it is local to constructor
newthread1()
{
t=new Thread(this,"FirstThread");
System.out.println("Child Thread:"+t);
t.start();
}

To create a thread in java there are two ways
1.By implementing Runnable interface.
2.By extending Thread class.
If you implement Runnable interface then you need to pass Runnable object to the Thread
constructor.
So that your object will get Thread behavior.
If you extends Thread class then you need create object of your Thread extended class.
So that your object will get Thread behavior.
But you have not followed any of the above two ways,
In your code the statement newthread1 t11 = new newthread1(); creates only simple object
not the Thread object.
But your trying to invoke Thread methods on normal object that leads to compilation errors.
To avoid errors you need to follow any one of above two ways.
More specific you have to
replace newthread1 t11 = new newthread1(); with this statement
Thread thread = new Thread(new newthread1());//first way implements Runnable
or replace class newthread1 implements Runnable{ with this statement
class newthread1 extends Thread implements Runnable{//second way extends Thread

I'm trying to use isALive
There is no such method. Do you mean isAlive()?
and join method but its throwing an error like can not find symbol
That's a compile error, probably because of the mis-spelling. Compile errors are printed, not 'thrown'.
please tell me where is the error exactly in this program.
The compiler has already done that, and you haven't posted it here. If you're expecting someone else to recompile your program for you just to find the error site, I suggest you may have a long wait.
and what is the use of join method.i know that it is a wait for threads to finish but i want in details.
The details are to be found in the Javadoc. I could quote it here but frankly I can't see the point when you should already have read it. If there was something there you didn't understand, you should have said so in your question.

Related

How to create n threads and work with all of them

Im trying to create a given number of threads and treat them at the same time to make a "race" program. The threads are created but im doing something wrong because any of the threads prints "Hi".
public class Principal implements Runnable{
public static void main(String[] args) {
int howManyThreads = 3;
Thread thread[];
thread = new Thread[howManyThreads];
for ( int i=0; i < thread.length; i++ ){
thread[i]= new Thread();
thread[i].setName("Thread - " + i);
}
for ( int i=0; i < thread.length; ++i){
thread[i].start();
System.out.println(thread[i].getName() + " - " + thread[i].getState());
}
}
public void run() {
System.out.println("Hi");
}
}
The default constructor for the Thread class creates a thread that does nothing. You're calling that default constructor here: thread[i] = new Thread();
If you want the thread to actually do something, then you must provide a Runnable instance as an argument to the Thread constructor. There are a couple of ways to do that. The newest, most concise way is to use a lambda expression:
thread[i] = new Thread(() -> {
System.out.println("Hi");
});
The Runnable interface is an #FunctionalInterface. Since the compiler knows that the Thread(...) constructor wants an object of that type, it infers that that's what the lambda should create, and the body of the lambda becomes the run() method of the new object.
Another, older way to provide a Runnable object is to use an anonymous inner class expression. The syntax is a little more cumbersome because you have to explicitly say what interface the new class should implement, and you have to explicitly declare the run() method:
thread[i] = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Hi");
}
});
The oldest way, still even more verbose, is to explicitly declare a named class:
class MyRunnable implements Runnable {
#Override
public void run() {
System.out.println("Hi");
}
};
public class Principal /*does not need to implement Runnable*/ {
...
thread[i] = new Thread(new MyRunnable());
...
}
You might ask, why did I remove implements Runnable from the Principal class, and create a whole new class?
I did it because, I've read this book: https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/

HOW TO USE Sleep Method within my finder class

I am working on a multi-thread program. Can someone please help me on how to implement the sleep method within my program. I have never used it and the requirement is that the run method uses the sleep method. I did start 4 threads and checked the outlined ranges. and I should Modify the Finder class so its run method utilizes the sleep method. I have never used the sleep method.
import static java.lang.System.out;
class Range
{
int start;
int end;
Range(int s, int e)
{
start = s;
end = e;
}
boolean contains(int x)
{
return end - start >=0;
}
}
class Finder implements Runnable
{
#Override
public void run()
{
}
}
public class ThreadTest implements Runnable
{
static void log(Object o){out.print(o);}
static void logLn(Object o){out.println(o);}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* #see Thread#run()
*/
#Override
public void run()
{
logLn("Running main");
}
static Range myRange = new Range(100, 500);
public static void main(String[] args)
{
if (myRange.contains(300))
{
System.out.println ("You\'re within the correct range.");
}
Finder fc = new Finder();
Thread t1= new Thread(fc);
t1.start();
Thread t2= new Thread(fc);
t2.start();
Thread t3 = new Thread(fc);
t3.start();
Thread t4 = new Thread(fc);
t4.start();
Runnable myRunnable = new Runnable(){
public void run(){
System.out.println("Runnable running");
}
};
myRunnable.run();
}
}
Sleep is a static method provided by the Thread class via Thread.sleep(1000L) where the value you pass is a Long representing milliseconds. Implementing a sleep method doesn't make much sense but calling Thread.sleep() will suspend the current thread that is executing that call.
So my guess is that you are supposed to call Thread.sleep within the run function of Finder.
EDIT
Implementing would simply be calling what I explained:
class Finder implements Runnable{
#Override
public void run(){
System.out.println("Thread " + Thread.currentThread().getId() + " sleeping");
Thread.sleep(1500L);
System.out.println("Thread " + Thread.currentThread().getId() + " awake");
}
}

Class implements Runnable but start() and sleep() methods are not defined

I've created a class called Thread that implements Runnable but I cannot invoke the start() or sleep() methods for some reason. Any time I attempt to do so, I get errors saying that these methods are undefined for the class and suggests that I create them. So I created a new project and copied a sample code to see if there was something wrong with my own code and I received the same errors. Here's the sample code:
class Thread implements Runnable {
private int a;
public Thread (int a) {
this.a = a;
}
public void run() {
for (int i = 1; i <= a; ++i) {
System.out.println(Thread.currentThread().getName() + " is " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
and this is my own code:
public class Thread extends PID implements Runnable {
public Thread() {}; // Empty constructor for thread object
public void run() {
Random gen = new Random(); // Generates random values
int sleepTime; // Sleep time
sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
try {
Thread.sleep();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The thread has been terminated");
}
}
To fix your current error, simply rename your Thread class to MyThread (or whatever), because your Thread class is hiding the java.lang.Thread class.
If you want to stick to Thread, you'll have to use the fully qualified name for java.lang.Thread like this:
try{
java.lang.Thread.sleep(1000);
// ...
Mistakes
Change class name from Thread to MyThread.
run() is called when you invoke start(). Invoke start() using class object.
Thread.sleep(); needs an argument say, sleepTime
Here is the code of what I think you want to do. Tested on Eclipse Juno JDK 1.7
import java.util.Random;
class NewThread implements Runnable {
public NewThread () {
}
public void run() {
Random gen = new Random(); // Generates random values
int sleepTime; // Sleep time
sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
try {
Thread.sleep(sleepTime);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The thread has been terminated");
}
}
class MyThread {
public static void main(String[] args) {
NewThread t = new NewThread();
Thread t1 = new Thread(t);
t1.start();
}
}
Output
The thread has been terminated
Interface Runnable do not have methods start() and sleep(), so be carefull with it. Interface Runnable only have run() method, and Java API recommends " the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods."
See Java API's Runnable documentation here: http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html
In every other cases, your class should extned class Thread.

services (threads) in sequence java

i have a task to make 3 (A,B,C) services depending on each other. When service A starts, service B can start, when service B starts , service C can start and when C stops, B can stop, and when B stops A can stop.
I have manage to start threads and make a switch from one to another with status option. I have to say that i dont know so much things about java but i have just started to learn java so i'm new in this so any help,suggestion and etc would be great.
Also I have 3 almost the same classes so can anyone tell em how can I replace those 3 classes with one? Is there any way?
Here is my code:
public class service_class {
int status=1;
public static void main(String[] args) {
service_class service_class = new service_class();
A1 a=new A1(service_class);
B1 b=new B1(service_class);
C1 c=new C1(service_class);
a.start();
b.start();
c.start();
}
}
class A1 extends Thread{
service_class service_class;
A1(service_class service_class){
this.service_class = service_class;
}
#Override
public void run() {
try{
synchronized (service_class) {
while(service_class.status!=1){
service_class.wait();
}
System.out.print("A started" + "\n");
service_class.status = 2;
service_class.notifyAll();
while(service_class.status!=7){
service_class.wait();
}
System.out.print("A stoped" + "\n");
service_class.status = 1;
service_class.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception 1 :"+e.getMessage());
}
}
}
class B1 extends Thread{
service_class service_class;
B1(service_class service_class){
this.service_class = service_class;
}
#Override
public void run() {
try{
synchronized (service_class) {
while(service_class.status!=2){
service_class.wait();
}
System.out.print("B started " + "\n");
service_class.status = 4;
service_class.notifyAll();
while(service_class.status!=6){
service_class.wait();
}
System.out.print("B stoped" + "\n");
service_class.status = 7;
service_class.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception 2 :"+e.getMessage());
}
}
}
class C1 extends Thread{
service_class service_class;
C1(service_class service_class){
this.service_class = service_class;
}
#Override
public void run() {
try{
synchronized (service_class) {
while(service_class.status!=4){
service_class.wait();
}
System.out.print("C started" + "\n");
service_class.status = 5;
service_class.notifyAll();
while(service_class.status!=5){
service_class.wait();
}
System.out.print("C stoped" + "\n");
service_class.status = 6;
service_class.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception 4 :"+e.getMessage());
};
}
}
I have 3 almost the same classes so can anyone tell em how can I replace those 3 classes with one? Is there any way?
It looks like the differences between the 3 classes A, B and C are:
the name string that gets printed, and
the state values that each one tests and sets.
So just replace these with final instance variables, and initialize them with values passed to the (unified) classes constructor.
However ...
Extending Thread is generally thought to be a bad idea. For a start, it makes it difficult to use thread pooling. A better approach is to use the standard Thread class, and pass it a Runnable instance when you construct it. In fact, if you are using thread pooling or and Executor service or whatever, you won't even need to create and manage the threads yourself.
As for the wait / notify stuff, it is easier to use a higher level synchronization construct (such as CountDownLatch).
Use CountDownLatch
A CountDownLatch is initialized with a given count. The await method block until the count reaches zero due to invocations of the countDown() method (by other threads), after which all waiting threads are released. My suggestion is writing a superclass that:
provides a latch with a initial count of 1
accepts another instance of that class or a CountDownLatch that is to be waited before execution
decrements its latch on start
wraps that logic in run and provides an abstract method innerRun where the actual code will be implemented.
abstract class LatchedRunnable extends Runnable {
private CountDownLatch latch=new CountDownLatch(1);
private CountDownLatch wait;
public Foo(LatchedRunnable waitFor) {
this.wait=waitFor.latch;
}
public Foo(CountDownLatch waitFor) {
this.wait=waitFor;
}
final run () {
//wait for the other thread
if (wait!=null)
try {wait.await();}
catch (InterruptedException e) {return;}
//signal that we have started
latch.countDown();
//actually start
innerRun();
}
protected abstract void innerRun(); //do stuff here
}
class Foo extends LatchedRunnable {
Foo(LatchedRunnable waitFor) {super(waitFor);}
protected void innerRun() {...}
}
class Bar extends LatchedRunnable {
Bar(LatchedRunnable waitFor) {super(waitFor);}
protected void innerRun() {...}
}
Foo foo = new Foo(null);
Bar bar = new Bar(foo);
CountDownLatch, in my understanding, is a mechanism to achieve synchronization without entering a deadlock. So here it goes,
Consider, Thread1 performs a task such a file read. Once complete file has been read, another thread could process the file contents and grab certain information. And now a third thread is responsible to copy the information to a DB.
Assume there are multiple clients using the same steps above and in the same order:
FileRead
FileProcessor
DBUpdate
Instead of handling everything sequentially, we create three thread pools.
ThreadPool<FileReaderThread> poolA;
ThreadPool<FileProcessorThread> poolB;
ThreadPool<DBUpdate> poolC;
As a new request comes in, a countdownlatch will be created with an appropriate count. As a thread from poolA completes its work, the count will be decremented. Once this count reaches 0, thread from poolB will be invoked.Similarly another countdownlatch will used to synchronize thread from poolB and poolC. Ideally, we achieve a sequential process with CountDownLatch.
Please correct if something is incorrect.

Problem with java semaphore

I am new to java and I am just trying to get feel of this language with the following example.Can anyone tell why the following program only shows:
calling prod
calling cons
import java.util.concurrent.*;
public class Trial5 {
static public void main(String[] arg){
new Prod();
new Cons();
}
}
class Q {
static Semaphore semc = new Semaphore(0);
static Semaphore semp = new Semaphore(1);
static int q[];
}
class Cons implements Runnable{
Thread t;
Cons () {
System.out.println("calling cons");
Thread t = new Thread();
t.start();
}
public void run () {
System.out.println("Running semc");
try {
System.out.println ("Waiting for Data.Acquiring semc");
Q.semc.acquire ();
if(Q.q[0] != 0) {
System.out.println(Q.q[0]);
Q.q[0] = 0;
} else {
wait ();
}
System.out.println ("Releasing semc");
Q.semc.release ();
}
catch (Exception e) {
System.out.println (e.getMessage());
}
}
}
class Prod implements Runnable {
Thread t;
Prod () {
System.out.println ("calling prod");
t = new Thread ();
t.start ();
}
public void run() {
System.out.println ("running semp");
try {
System.out.println ("Waiting for Data.Acquiring semp");
Q.semp.acquire ();
if (Q.q[0] == 0) {
System.out.println ("setting value semp");
Q.q[0] = 10;
} else {
Thread.sleep(100);
}
System.out.println ("Releasing semp");
Q.semp.release ();
}
catch (Exception e) {
System.out.println (e.getMessage());
}
}
}
Your problem isn't with Semaphore, it's with your threads. Your run method is not executing because you're instantiating new instances of Thread which have no idea about the classes you've created and running those rather than doing anything with the classes you've created. So your run methods are never getting called.
Specifically, the lines like this:
Thread t = new Thread();
t.start();
have no reference to the classes they are contained in. They just create a new Thread object which has only the default run method and then start it.
This site has examples of how Threads get run (either through extending Thread or by implementing Runnable). You're going to have to restructure your code some to get it to work, though. Although it might work to simply change the lines to read
Thread t = new Thread(this);
that's a bad idea since you'd be passing the object as a value while its constructor is still running. A better idea would be to have your main method construct each object and then use them to start the threads running.
Furthermore:
Always use semaphores in a
try-finally block. So that whatever
happens you always release the
semaphore, otherwise a deadlock is
bound to happen.
You're calling 'wait()' (which is is a method of the Runnable (inherited from Object) instance) but you can't because you don't own the lock. For more on this see Monitor
Thread.sleep(100) actually throws an InterruptedException: catch it and re-interrupt the thread as the interrupted flag is cleared when InterruptedException is thrown. For more on this topic see for instance Dealing with InterruptedException
You need to do
t = new Prod();
and
t= new Cons();
see here for further reference:
http://www.exampledepot.com/egs/java.lang/BasicThread.html

Categories