I am new to threads and while learning it i cant understand the following,
public class myClass
{
public static void main(String args[]) throws InterruptedException
{
String[] myString = {"Object","Classes","Static","Final"};
for(int i=0;i<myString.length;i++)
{
System.out.println(myString[i]);
Thread.sleep(2000);
}
}
}
How come I'm able to use thread method without extending Thread class?
sleep is a static method. It doesn't require an instance to be called.
There are only 2 ways to make a class/method 'threadable' in Java. Extending Thread or implementing Runnable. What you are doing there is Thread.sleep() which is simply saying sleep the current thread.
It is just a static method supplied by Thread and as you have discovered doesn't really have much to do with multithreading specifically. A static method means an object of the containing class does not need to be instantiated to invoke the method which is why you can call sleep() without extending Thread.
Read about static methods in the Java tutorial. Learn the basics of the language before playing with threads. Threads are a difficult thing to master, and if you don't know what a static method is, it's too early to start using them, IMHO.
Here you are using astatic member method of Thread class, that's why you are able to use the sleep() function without requiring an instance.
sleep() is a static method of the 'Thread' class. as you might know static methods are invoked directly by the sysntax
MyClass.myStaticMethod().
you don't need to instantiate a Thread object to call sleep() method.
Related
Why sleep() and yield() methods are defined as static methods in java.lang.Thread class?
The code would only execute when someXThread was executing, in which case telling someYThread to yield would be pointless. So since the only thread worth calling yield on is the current thread, they make the method static so you won't waste time trying to call yield on some other thread.
This is because whenever you are calling these methods, those are applied on the same thread that is running.
You can't tell another thread to perform some operation like, sleep() or wait. All the operation are performed on the thread which is being executed currently.
If you call the yield or sleep method, it applies to whichever thread is currently executing, rather than any specific thread - you don't have to specify which thread is currently running to free up the processor.
similar thread in this forum
The same reason is why stop() and suspend() methods are deprecated. Intrusion in thread's state from outside is dangerous and can cause unpredictable result. And if sleep is not static, for example, how do you think interruption from it will happen?
They are static so that overriding concept can be avoided i.e.
When they are called with parent class reference to hold child class object like situation it implements Method Hiding concept and not overriding due to Static method nature, i.e parent class(here thread class) method will run which have the complete functionality of sleep and yield.
http://i.stack.imgur.com/goygW.jpg
Both sleep and yield methods are native. To understand better from above answers I made two classes ClassA and ClassB with same static method. I invoked method of other class to check its behavior. So we can call other class' static method.
So may be there is other reason behind making sleep method static.
public class ClassA {
public static void method(){
System.out.println("Inside ClassA method");
}
public static void main(String[] args) {
method();
ClassB classb = new ClassB();
classb.method();
}
}
public class ClassB {
public static void method(){
System.out.println("Inside ClassB method");
}
}
I know I am late to this party, (blame my parent :-))
I would like to answer this using proof by contradiction.
Let's say sleep method is not static so you can call sleep on any other thread object.
Let's say there are two threads, thread A and thread B. Now consider two possible scenarios in the context of sleep method, the same applies to yield as well.
System having single processor has only one thread active at a time, so if thread A calls sleep on thread B object i.e. B.sleep(), B is not in execution, as currently executing thread is thread A, so calling sleep on non-executing method is pointless.
A responsible programmer would never define sleep inside a synchronized block, or when a thread is holding a lock. But let's say thread A calls sleep method on thread B just when thread B is holding a lock(or inside a synchronized block), thread B would go to sleep holding lock which is totally undesirable.
These are just a few situations which forced jvm to not allowed thread to call sleep on another thread obect.
consider the following code snippet
public class ThreadDemo{
public static void main(String[] args){
Thread t = Thread.currentThread();
t.setName("MainThread");
}
}
I know that each class automatically extends java.lang.Object. and this class does not extend or implement any other class or interface.
my question is since the class ThreadDemo is NOT extending or implementing any interface or class including Thread and Runnable.
How it is possible for us to use the class Thread in the main method to access the main thread?
I mean how it works??? Is it something about the JVM stuff?
You're calling the static currentThread() method of Thread, which returns the current thread (hence the name). Then you set its name.
There's nothing magical about this code (except that currentThread() is a native method).
how the JVM knows that I mean the main thread NOT any other thread?
The name "currentThread" is a bit of a misnomer. It dates back to a time when most computers had only one CPU, and so only one thread---the current thread---could be running at any given time.
On my laptop, there can be eight "current" threads, and on a big mainframe, there can be more than a hundred. What Thread.currentThread() does these days is return the identity of whatever thread called the method.
currentThread( ) is a public static member of the Thread class. It's general form is:
static Thread currentThread( )
This method returns a reference to the thread in which it is called.
Static methods can be called without creating an instance of the class, using the class name as follows:
ClassName.staticMethod( )
Since currentThread( ) is a static member method it is therefore used directly without creating an instance of the Thread class.
If a class has only two synchronized methods (both either static or non static), the class is considered to be thread safe. What if one of the methods is static and one non static? Is it still thread safe, or bad things can happen if multiple threads call the methods?
There are some similar threads like static synchronized and non static synchronized methods in threads which describe the method calls are not blocking each other. But I am curious to know whether bad things in the world of thread safety (like inconsistent state, race condition, etc) can happen or not.
Edit 1:
Since static methods can't call non static methods, there should be no thread conflict from this side. On the other hand if a non static method calls the static one, it has to acquire the class lock. Which would be still thread safe. So by just having two methods (one static one none) I don't see any thread conflict. Is that right? In other words the only case I can see to have an issue is when the non static method accesses some static variables. But if all accesses are done through methods then I don't see any issues with thread safety. These were my thoughts. I am not sure whether I am missing something here since I am a little bit new to java concurrency.
In Java, the following:
public class MyClass
{
public synchronized void nonStaticMethod()
{
// code
}
public synchronized static void staticMethod()
{
// code
}
}
is equivalent to the following:
public class MyClass
{
public void nonStaticMethod()
{
synchronized(this)
{
// code
}
}
public void static staticMethod()
{
synchronized(MyClass.class)
{
// code
}
}
}
As you see, static methods use this as monitor object, and non-static methods use class object as monitor.
As this and MyClass.class are different objects, static and non-static methods may run concurrently.
To "fix" this, create a dedicated static monitor object and use it in both static and non-static methods:
public class MyClass
{
private static Object monitor = new Object();
public void nonStaticMethod()
{
synchronized(monitor)
{
// code
}
}
public static void staticMethod()
{
synchronized(monitor)
{
// code
}
}
}
What if one of the methods is static and one non static? Is it still thread safe, or bad things can happen if multiple threads call the methods?
Bad things can happen.
The static method will lock on the class monitor. The instance method will lock on the instance monitor. Since two different lock objects are in use, both methods could execute at the same time from different threads. If they share state (i.e. the instance method accesses static data) you will have problems.
What if one of the methods is static and one non static? Is it still thread safe, or bad things can happen if multiple threads call the methods?
Synchronization works with monitor (locks) that is taken on object.
In case of static method it's object of Class's class and in case of instance method it's this or calling object.
Since both the objects are different hence both synchronized static and non-static method will not block each other in case of multi-threading. Both the methods will execute simultaneously.
What if one of the methods is static and one non static
Yes.. Bad things can happen. Because if you synchronize on a static method, then you will be locking on the monitor of the Class object not on the class instancei.e, you will be locking on MyClass.class.
Whereas when you are synchronizing on an instance (non-static) method, you will actually be locking on the current instance i.e, this . So, you are locking on two different objects. So, the behaviour will be undefined and certainly not correct.
PS : In multi-threading, as a rule of thumb, please remember - If bad things can happen, they will happen.
What if ... Is it still thread safe?
Can't answer that question without a complete example. The question of thread safety is never a question about methods: It's a question about corruption of data structures and about liveness guarantees. Nobody can say whether a program is thread safe without knowing what all of the different threads do, what data they do it to, and how they coordinate (synchronize) with one another.
This is a piece of code I am using as an example of how to run multiple threads:
import javax.swing.SwingUtilities;
public class ThreadDem {
//field
Runnable doRun;
//constructor
public ThreadDem(){
//instantiates a runnable object
doRun = new Runnable(){
//have to override the abstract method run of runnable and am
//declaring method here in this block statement
#Override
public void run() {
System.out.println("Hello from thread: "
+ Thread.currentThread());
}
};
}
public static void main (String[] args){
ThreadDem demo = new ThreadDem();
System.out.println("Hello this is from thread: " +
Thread.currentThread());
//I use the invokelater method to invoke the run method of do run on a
//seperate thread
SwingUtilities.invokeLater(demo.doRun);
}
}
I more or less just took it from the docs on runnable. However I am finding it hard to understand why it works like this. I am still new to OOP and don't really understand how I can instantiate an interface(runnable) and if indeed my runnable object is not a class how can I define it a method(run())... can someone please explain to me in simple terms step by step exactly what is happening in that constructor so I can make sense of the process? Thankyou!
What you have created is called an Anonimous class. The link contains the official tutorial which explains what it is, but in a nutshell - you created a one-off class implementing Runnable and instantiated an object of said class.
As a suggestion - Don't try to tackle multithreading before you grasp the basic concepts of the language like OOP and grammar.
In Java interfaces can not be instantiated, they are simply guidelines of what a method must implement in order to implement that interface. In order to instantiate a thread in Java it's best to use
public class ThreadDem extends Runnable (recommended)
or
public class ThreadDem extends Thread.
At that point you're required to implement a "public void run" method that overwrites the empty one from Runnable. At that point you can simply call run on any object of type ThreadDem.
I just started learning java and I ran into a slight road block involving threads. I have a static method that I would like to run in its own thread, is this possible? In python I know it would look something like this:
import thread;thread.start_new_thread( my_function, () );
And I know how to use threading with non-static methods by implementing Runnable or extending thread, but this is not what I am trying to do.
Have a Thread's run method call the static method:
new Thread(Call::yourStaticMethod).start();
The above would create a Static Method that executes in another Thread:
public static void yourStaticMethod() {
new Thread(new Runnable(){
// This happens inside a different Thread
}).start();
}
You need to create a new Thread.(As far as I understand)
Thread t = new Thread(){
#Override
public void run(){
method();
}
static void method(){// do stuff
}
}
//finally
t.start();
You can always make a class inside a method and pass more arguments to the thread.
You dont need to wrap Runnable with Thread. Use whichever you like, it is the same thing!
The fact that the method is static is of little importance here.
If the static method really does only use local variables, no object fields or methods, then it is thread-safe. If it accesses any object fields or methods, it may not be thread-safe, depending on what those fields or methods are used for, in other code.
You can either create a new thread inside of a static method or other stuff. It depends on what you want to do.
If you are using Java 8+, you can also use Java lambda expresions. Like this:
new Thread(()-> MyApp.myStaticMethod()).start();