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.
Related
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");
}
}
Doing a threading problem and I am not sure if this is how its supposed to be or if I coded incorrectly. From what I understand, threading should have multiple methods going at the same time and because of this they should be intertwined. My code is supposed to take a single char and repeat 1000 times but instead of having different variations of the two letters it goes "a" a thousand times, then "b" a thousand times. What is my issue?
Main Method
import java.util.*;
public class MainThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner answer = new Scanner(System.in);
System.out.println("Give me a single character: ");
char h = answer.next().charAt(0);
System.out.println("Give me another single character: ");
char a = answer.next().charAt(0);
MyThread t1 = new MyThread(h);
MyThread t2 = new MyThread(a);
t1.start(h);
t2.start(a);
answer.close();
}
}
my Threading class
import java.util.*;
public class MyThread extends Thread{
Scanner answer = new Scanner(System.in);
public MyThread(char x) {
// TODO Auto-generated constructor stub
}
public void Stored(char x){
System.out.println("Type a single letter here: ");
}
//modified run method
public void start(char x){
for(int i = 0; i < 1000; i++){
System.out.print(x);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
}
}
What you have done is NOT multithreading, rather you have called the start method sequentially, i.e., in order to run the multiple threads parallelly, you need to override the run() method in your MyThread class.
The important point is that run() method will be called by JVM automatically when you start the Thread, and the code inside run() will be executed in parallel with the main/other threads, so override run() inside MyThread class as shown below:
class MyThread extends Thread {
private char x;
public MyThread(char x) {
this.x= x;
}
// Add run() method
public void run() {
for (int i = 0; i < 10; i++) {
System.out.print(x);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
}
}
MainThread class:
public class MainThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner answer = new Scanner(System.in);
System.out.println("Give me a single character: ");
char h = answer.next().charAt(0);
System.out.println("Give me another single character: ");
char a = answer.next().charAt(0);
MyThread t1 = new MyThread(h);
MyThread t2 = new MyThread(a);
t1.start();//this calls run() of t1 automatically
t2.start();//this calls run() of t2 automatically
answer.close();
}
}
I suggest you have a look here for basic understanding on how to create and start the Thread and how multi-threading works.
In order to let the threads run in parallel, the run method needs to be implemented instead of start.
See the JavaDoc for Thread.start():
Causes this thread to begin execution; the Java Virtual Machine calls
the run method of this thread.
The result is that two threads are running concurrently: the current
thread (which returns from the call to the start method) and the
other thread (which executes its run method).
First of all, it's not guaranteed that your described behavior will never occur, even when you implement a correct multithreading. But, it shouldn't be repeatable ;)
The solution is: don't override the start() but the run() method.
The thread constructor should take the argument, the start() is called (and no new start method with an argument!) from the main, and the run() implements the job that is executed parallel. Therefore, you can access the thread's field which you set in your thread constructor.
The error was already explained: the start method is being overridden instead of the run method. Anyway it is not recommended to extend the Thread class since you are not wanting to extend its functionality.
You just want to use a Thread, so a better approach (IMO) is to provide a Runnable to the Thread:
public static void main(String[] args) {
// ...
Thread t1 = new Thread(new MyRunnable(h));
t1.start();
}
The Runnable (use a better Name in production code):
public class MyRunnable implements Runnable {
private final char ch;
public MyRunnable(char theChar) {
ch = theChar;
}
#Override
public void run() {
for (int i = 0; i < 1000; i++) {
...
}
}
This could be improved using with Lambda, but is not the point here
More: "implements Runnable" vs. "extends Thread"
public class TestSynchronization {
public static void main(String[] args) {
ThreadTest[] threads = new ThreadTest[10];
int i = 0;
for(Thread th : threads) {
th = new Thread(Integer.toString(i++));
th.start();
}
}
class ThreadTest extends Thread {
TestSynchronization ts = new TestSynchronization();
public /*synchronized */void run() {
synchronized(this) {
ts.testingOneThreadEntry(this);
System.out.println(new Date());
System.out.println("Hey! I just came out and it was fun... ");
this.notify();
}
}
}
private synchronized void testingOneThreadEntry(Thread threadInside) {
System.out.println(threadInside.getName() + " is in");
System.out.println("Hey! I am inside and I am enjoying");
try {
threadInside.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I am not able to start the ThreadTest instances.
I expect that ThreadTest's run method be executed as soon as the line th.start(); is executed, the one inside main method.
When I run the program, I see niether my system.out nor any exception.
I debugged also, but could see loop runs 10 times.
You just started a Thread, not a ThreadTest. Thread's run() method does nothing. Instead, create and start() a ThreadTest.
for(ThreadTest th : threads) {
th = new ThreadTest(Integer.toString(i++));
th.start();
}
You'll also need a one-arg constructor in your ThreadTest class that will take the String you're passing to it.
public ThreadTest(String msg){
super(msg);
}
You'll also need to make the ThreadTest class static so you can access that nested class from the static main method.
static class ThreadTest extends Thread {
However, you'll wind up will all Threads waiting. As written, this code will call wait inside every Thread, but it will never get to notify. The notify method must be called on the Thread to be notified, from another Thread. If it's waiting, then it can never notify itself.
You have array of ThreadTest (thread) class which is not used.
I assume you wanted this:
public static void main(String[] args) {
ThreadTest[] threads = new ThreadTest[10];
int i = 0;
for(int i=0;i<threads.length;i++) {
threads[i] = new ThreadTest();
threads[i].start();
}
}
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.
Not sure sure if I am doing this right. I need to make a new thread to write out message certain number of times. I think this works so far but not sure if its the best way of doing it. Then i need to display another message after thread has finished running. How do I do that ? Using isAlive() ? How do i implement that ?
public class MyThread extends Thread {
public void run() {
int i = 0;
while (i < 10) {
System.out.println("hi");
i++;
}
}
public static void main(String[] args) {
String n = Thread.currentThread().getName();
System.out.println(n);
Thread t = new MyThread();
t.start();
}
}
Till now you are on track. Now, to display another message, when this thread has finished, you can invoke Thread#join on this thread from your main thread. You would also need to handle InterruptedException, when you use t.join method.
Then your main thread will continue, when your thread t has finished. So, continue your main thread like this: -
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Your Message");
When your call t.join in a particular thread (here, main thread), then that thread will continue its further execution, only when the thread t has completed its execution.
Extending the Thread class itself is generally not a good practice.
You should create an implementation of the Runnable interface as follows:
public class MyRunnable implements Runnable {
public void run() {
//your code here
}
}
And pass an intance of it to the thread as follows:
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
Please check this answer here on SO: Implementing Runnable vs. extending Thread
This is how you can do that.........
class A implements Runnable
{
public void run()
{
for(int i=1;i<=10;i++)
System.out.println(Thread.currentThread().getName()+"\t"+i+" hi");
}
}
class join1
{
public static void main(String args[])throws Exception
{
A a=new A();
Thread t1=new Thread(a,"abhi");
t1.start();
t1.join();
System.out.println("hello this is me");//the message u want to display
}
}
see join() details on
join