I have written a simple java program and I was hoping for an output like
go
hello
bye //pause for 2 seconds
hello
But it is giving an output like
go
bye
hello //pause for 2 sec
hello
Programme:
class Tread{
public static void main(String[] args){
Hello h= new Hello();
Thread t= new Thread(h);
System.out.println("go");
t.start();
System.out.println("Bye");
}
}
class Hello implements Runnable{
public void run(){
System.out.println("hello");
try{
Thread.sleep(2000);
}
catch(Exception e){ }
System.out.println("hello");
}
}
Please, can anybody tell me why i am not getting the desired otput?
The result is unpredictable since 2 threads try to write something on the output simultaneously. The JVM specs do not specify the order of the operations:
you have the main thread that starts another thread
after that, the main thread and the other thread both print something.
So, all of this is implementation dependant: somebody may use another JVM, one day, and/or another operating system, and he could then have another behaviour. With your JVM, on your environment, you may encounter millions of run of this program writing output in the same order. But it does not mean that it will never change in the future.
If you want the sequence of operations to be done according to a particular order, you need to use some locks, or synchronized keyword to access resources.
Thinking it will always behave the same often leads to mistakes, that happen only occasionally, and that we call race conditions.
I guess because it is on another thread, independent from main program.
Try this:
public static void main(String[] args){
Hello h= new Hello();
Thread t= new Thread(h);
System.out.println("go");
t.start();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Bye");
}
}
class Hello implements Runnable{
public void run(){
System.out.println("hello");
try{
Thread.sleep(2000);
}
catch(Exception e){}
System.out.println("hello");
}
}
Related
According to the information I've got so far, I've understood that Thread.sleep() pauses the thread where the method is called. For example, if I call it within the main method it pauses the execution of main. if I call it inside the run of a certain thread, it would only pause that thread.
I need an expertise to confirm my understanding as I feel lost among the too much information on web.
I've been practicing to apply this, throw the following:
a Thread class, Player1:
public class Player1 extends Thread{
public void run()
{
try {
System.out.println("I'm going to sleep");
Thread.sleep(2000);
System.out.println("I'm awake");
} catch (InterruptedException ex) {
}
}
}
a Thread class, Client:
public class Clients extends Thread {
public void run()
{
printer2(10);
}
public synchronized static void printer2(int val)
{
System.out.println(val);
System.out.println(val);
System.out.println(val);
System.out.println(val);
System.out.println(val);
System.out.println(val);
}
}
they're called inside main method:
public static void main(String[] args) throws InterruptedException {
Clients c1 = new Clients(10);
Player1 p = new Player1();
p.start();
c1.start();
}
What happens (according to my understanding): the sleep is applied only to the execution of the player1 thread not to the main thread or the client thread.
Similarly, if I add a sleep method in the run of the Clients thread, it would sleep independently of the other Thread. for instance: this sleeps for its own 1 second and this sleeps for its 1 second as well (even if those 2 1 seconds overlap)
Correct me if I'm wrong please
Thanks in advance!
i am new to multithreading and trying to clear my basics.
public class SleepExample extends Thread {
private int counter = 0;
#Override
public void run() {
try {
counter++;
System.out.println("Value of counter "+counter);
System.out.println("Thread going in sleep "+Thread.currentThread().getName());
Thread.currentThread().run();
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("Thread out of sleep "+Thread.currentThread().getName());
}
public static void main(String[] args) {
new SleepExample().start();
new SleepExample().start();
Test test = new Test();
Thread t = new Thread(test);
t.start();
}
}
//another class implementing runnable
public class Test implements Runnable {
#Override
public void run() {
System.out.println("In Test runnable method");
}
}
When i run this code, my run method of SleepExample recursively call itself after below line
Thread.currentThread().run();
for thread belonging to SleepExample (Thread -0, Thread -1) and
it goes to run method of Test class for thread t.
I am unable to understand the usage of Thread.currentThread().run();
P.S. - I read its java doc and so i have implemented a runnable
I am unable to understand the usage of Thread.currentThread().run();
You are not supposed to call it directly. From Thread.start() You are supposed to use start() to call run() and that is it.
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).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
You are already running in the run() so you should only call this if you can say why you are doing it, even then it will look like a bug or be plain confusing and I would suggest you use a loop instead.
When i run this code, my run method of SleepExample recursively call itself after below line
You have a method calling itself, so you should expect that to happen. There is nothing special to Thread in this regard. It is like any other recursive call in a method.
I have two CLASS(each has a thread), and I want to create a queue shared between them. So one class could write some bytes to the queue, and the other can read from the SAME queue.
I tried static, and here are my codes:
public class ShareQueueTest {
public static final BlockingQueue<byte[]> memshare= new ArrayBlockingQueue<>(1000);
public static void main(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
try {
memshare.put(new byte[20]);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(memshare.size());
}
}};
a.start();
}
}
And the other class is simple read from this queue.
public class ShareQueueTest2 {
public static void main(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
System.out.println(ShareQueueTest.memshare.size());
}
}};
a.start();
}
}
I run it. Though one thread is putting bytes in this queue, the other is still saying the queue is empty all the time. So clearly they are referred to the different things.
ALL the thing happens in local machine.
As this question is simplified from a network scenario, so for some reason, I don't want another class to manipulate those two threads, they are blind to each other. Perhaps the only thing they know for each other is that each thread running on the same local machine, plus, they know the port numbers of the other. Under such condition, I need some methodologies to create a data structure which both of them can 'see'.
I also think of using memory address. Like one class get the memory address of the object, and the other get the object from the address and cast it to the correct data structure. Is it possible in java?
Any help will be appreciated!
Since both of your classes have a main method, it appears that you may be running these two classes in separate processes (instances of the JVM)
If you call ShareQueueTest2.main(...) from ShareQueueTest.main, it should work
If you call the two classes separately, it would spawn two separate JVMs which are two separate processes. The thread cannot communicate across processes via a shared queue.
You need to start both the threads from the same code as the other answers point out. Then you can access the shared variables and see the changes done by one thread get reflected in the other thread.
Try this :
public class ShareQueueTest {
public static final BlockingQueue<byte[]> memshare= new ArrayBlockingQueue<>(1000);
public static void subMain(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
try {
memshare.put(new byte[20]);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(memshare.size());
}
}};
a.start();
}
}
public class ShareQueueTest2 {
public static void subMain(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
System.out.println(ShareQueueTest.memshare.size());
}
}};
a.start();
}
}
public class Launch
{
public static void main( String[] args)
{
ShareQueueTest1.subMain(args);
ShareQueueTest2.subMain(args);
}
}
Hy, i try to follow this http://www.studytonight.com/java/synchronization.php
here's my code
class First {
public void display(String msg)
{
System.out.print("["+msg);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
System.out.println("]");
}
}
class Second extends Thread{
String msg;
First fobj;
Second(First fp,String str){
msg=str;
fobj=fp;
start();
}
public void run(){
synchronized(fobj){
fobj.display(msg);
}
}
}
public class Main {
public static void main(String[] args) {
// TODO code application logic here
First f=new First();
Second s1=new Second(f,"welcome");
Second s2=new Second(f,"new");
Second s3=new Second(f,"programmer");
}
}
and here's my result
run:
[welcome]
[programmer]
[new]
BUILD SUCCESSFUL (total time: 3 seconds)
what's wrong with my code? why the result isn't welcome new programmer ?
All the threads start almost at the same time, and compete with each other to get the lock on the shared object.
There is no guarantee that the second thread asks for the lock before the third one. And even if that is the case, the lock is not fair, so there is no guarantee that the first thread waiting for the lock will get it first.
The only guarantee you can have with the above code is that only one of the thread will be able to execute the synchronized method at a time.
I'm new to threads. I wanted to create some simple function working separately from main thread. But it doesn't seem to work. I'd just like to create new thread and do some stuff there independently of what's happening on main thread. This code may look weird but I don't have much experience with threading so far. Could you explain me what's wrong with this?
public static void main(String args[]){
test z=new test();
z.setBackground(Color.white);
frame=new JFrame();
frame.setSize(500,500);
frame.add(z);
frame.addKeyListener(z);
frame.setVisible(true);
one=new Thread(){
public void run() {
one.start();
try{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v){System.out.println(v);}
}
};
}
You are calling the one.start() method in the run method of your Thread. But the run method will only be called when a thread is already started. Do this instead:
one = new Thread() {
public void run() {
try {
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v) {
System.out.println(v);
}
}
};
one.start();
You can do like:
Thread t1 = new Thread(new Runnable() {
public void run()
{
// code goes here.
}});
t1.start();
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start().
The result is a new instance of class Thread, which is called join().
You need to do two things:
Start the thread
Wait for the thread to finish (die) before proceeding
ie
one.start();
one.join();
If you don't start() it, nothing will happen - creating a Thread doesn't execute it.
If you don't join) it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.
Since a new question has just been closed against this: you shouldn't create Thread objects yourself. Here's another way to do it:
public void method() {
Executors.newSingleThreadExecutor().submit(() -> {
// yourCode
});
}
You should probably retain the executor service between calls though.
There are several ways to create a thread
by extending Thread class >5
by implementing Runnable interface - > 5
by using ExecutorService inteface - >=8
If you want more Thread to be created, in above case you have to repeat the code inside run method or at least repeat calling some method inside.
Try this, which will help you to call as many times you needed.
It will be helpful when you need to execute your run more then once and from many place.
class A extends Thread {
public void run() {
//Code you want to get executed seperately then main thread.
}
}
Main class
A obj1 = new A();
obj1.start();
A obj2 = new A();
obj2.start();
run() method is called by start(). That happens automatically. You just need to call start(). For a complete tutorial on creating and calling threads see my blog http://preciselyconcise.com/java/concurrency/a_concurrency.php
A simpler way can be :
new Thread(YourSampleClass).start();
Please try this. You will understand all perfectly after you will take a look on my solution.
There are only 2 ways of creating threads in java
with implements Runnable
class One implements Runnable {
#Override
public void run() {
System.out.println("Running thread 1 ... ");
}
with extends Thread
class Two extends Thread {
#Override
public void run() {
System.out.println("Running thread 2 ... ");
}
Your MAIN class here
public class ExampleMain {
public static void main(String[] args) {
One demo1 = new One();
Thread t1 = new Thread(demo1);
t1.start();
Two demo2 = new Two();
Thread t2 = new Thread(demo2);
t2.start();
}
}