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();
}
}
Related
its seems to be a stupid question but I'm trying to create a task in a new thread, and after the task is finished the thread should exit without calling anything to stop it from main.
Here is an example:
public class Main {
public static void main(String[] args) {
// write your code here
foo f1= new foo();
Thread t= new Thread(f1);
f1.doSomething();
}
}
class foo extends Thread{
void doSomething(){
// download File for example
}
}
if I implement the run method like this :
class foo extends Thread{
void doSomething(){
// download File for example
}
void run(){
doSomething();
}
}
it is going to call doSomething() method forever.
foo f1= new foo();
Thread t= new Thread(f1);
f1.doSomething();
This is not the away to start a thread. Basically you call thread.start() method to start the thread which will execute everything which is there in run method.
Please go through the tutorial first
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Here is one solution:
public class ThreadExample extends Thread {
private void doSomething(){
System.out.println("Inside : doSomething()");
}
#Override
public void run() {
System.out.println("Inside : " + Thread.currentThread().getName());
doSomething();
}
public static void main(String[] args) {
System.out.println("Inside : " + Thread.currentThread().getName());
System.out.println("Creating thread...");
Thread thread = new ThreadExample ();
System.out.println("Starting thread...");
thread.start();
}
}
One output:
Inside : main
Creating thread...
Starting thread...
Inside : Thread-0
Inside : doSomething()
For further informations, check out this Java Concurrency and Multithreading tutorial.
I am new to threads in Java and hence have this doubt. I read that a 'synchronized non-static method block' allows only one thread to enter the block (for one instance of non-static block, of-course). However it doesn't seem to work. Am I missing something?
Look at the following code.
class A extends Thread
{
public void run()
{
B.b.add();
}
}
class B
{
static B b=new B();
int i;
public synchronized void add()
{
i++;
}
}
public class Sample
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
new A().start();
}
System.out.println(B.b.i);
}
}
One problem here is that your main thread doesn't wait for the other threads to finish before it tries to retrieve the result. Using Thread#join works if you want to wait for a single thread, but here we want to wait for all 10. Modifying the program to use CountDownLatch makes the main thread wait until all the threads it created are finished.
Another problem is that the updated value of i isn't guaranteed to be visible. JVM implementations differ about how aggressively they perform optimizations (like delaying refreshes of cached values, or reordering bytecode) that may make the changes to i not visible to the main thread. Adding a synchronized method on the same lock as the add method to fetch the value of i fixes the visibility issue.
import java.util.concurrent.CountDownLatch;
class A extends Thread {
private CountDownLatch latch;
public A(CountDownLatch latch) {
this.latch = latch;
}
#Override public void run() {
B.b.add();
latch.countDown();
}
}
class B {
static B b=new B();
int i;
public synchronized void add() {
i++;
}
public synchronized int getI() {
return i;
}
}
public class Sample {
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(10);
for(int i=0;i<10;i++) {
new A(latch).start();
}
latch.await();
System.out.println(B.b.getI());
}
}
class myRunnable implements Runnable {
public void run() {
// TODO Auto-generated method stub
System.out.println("run");
}
}
public class TestThread {
public static void main(String[] args) {
Runnable threadJob = new myRunnable();
Thread t = new Thread(threadJob);
t.start();
for (int i = 0; i < 100000; i++) {
System.out.println("main");
}
}
}
Result in the console:
main
main
main
main
...
main
main
main
main
I can't find any "run" word, this means the run method didn't run. Can somebody explain that for me. Thank you.
PS: when i<10, i<100, i<1000, i<10000, I can find the "run" word, but when i<100000 then I can't find the "run" word, that's just weird
Run has been printed out. But your console-buffer is not large enougth.
Change the Console-configuration to unlimited buffer.
First of all, Yes, Your code actually prints "run".
Just make this little change below and You´ll see it.
A more rigorous test, If You can see it in a different way, is to send the strings to a text file instead of the console. You will certanly find the word "run".
class myRunnable implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("run");
}
}
public class TestThread {
public static void main(String[] args) {
Runnable threadJob = new myRunnable();
Thread t = new Thread(threadJob);
t.start();
for (int i = 0; i < 100000; i++) {
System.out.println("main");
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Your implementation runs just fine. You just don't see your run message because there hasn't been any thread switch just yet.
The problem is that the action on which you examine the threads is too short. You can insert a Thread.sleep(2000); for example to check it out.
I find this wired that you can't find a run in your output, the thing is that you should understand how the java thread mechanism works, the main thread will not wait for the child thread to complete their work, unless you make it specific, thus whether or not the child complete before the main thread complete (and exit) is not expectancy.
if you do want the main thread to wait for the child thread to complete, you can make it specific by:
t.start();
t.join();
You should have to catch some exception to make this work.
But I think it should be high ratio that you should see a run printed in your original code. because it seems the main thread is more time consuming.
regardless of this, there is nothing to blame if your jvm behave like this. the thread executing order is not insured by the standard anyway.
Simply add a delay of one second within the loop as displayed below:
class myRunnable implements Runnable {
public void run() {
System.out.println("run");
}
}
public class TestThread {
public static void main(String[] args) {
Runnable threadJob = new myRunnable();
Thread t = new Thread(threadJob);
t.start();
for (int i = 0; i < 100000; i++) {
System.out.println("main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
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
I am new to Java. Below is a code as an example of threads and synchronization.
public class A implements Runnable{
public synchronized void run(){
/*
some code here
*/
}
}
public class B {
public static void main(String[] args){
A obj1 = new A();
Thread t = new Thread(obj1);
A obj2 = obj1;
Thread t1 = new Thread(obj2);
t.start();
t1.start();
}
}
Now will this two threads block each other for same lock or will they get two different locks?
Thank you!!
(First, please stick to the Java coding conventions. A class name should always start with a capital letter. No exceptions.)
Only one of the threads will execute the run() method at a time.
The A.run() method is an instance method, and it is declared as synchronized. These two facts mean that it will acquire a lock on this (i.e. the instance of A) before entering the method body, and release it on exiting. In short, run() locks this.
So in your main program you are creating a single A instance and passing it as the target object for two threads. They both need to execute the run() method on the same object, and this cannot happen at the same time ... by the reasoning of the previous paragraph.
This does not necessarily mean that one thread will block the other. It is also possible that the first thread to be started will have completed its run() call before the second thread is ready to try the call. But we can say ... definitively ... that the two threads' calls to run() will NOT overlap in time.
They will block each other, since they're both synchronized on the same object.
For example, this program:
public class Foo
{
public static void main(final String... args)
{
final Runnable r =
new Runnable()
{
public synchronized void run()
{
for(int i = 0; i < 10; ++i)
{
System.out.println(i);
try
{ Thread.sleep(1000L); }
catch(final InterruptedException ie)
{ throw new RuntimeException(ie); }
}
}
};
new Thread(r).start();
new Thread(r).start();
}
}
will print 0 through 9, pausing for a second after number, and then do it again. It will not interlace the two sets of numbers.
Synchronization forces the threads to run in order (block).
Synchronization, by definition, means that a method is run "one at a time". The first thread to be executed (likely "t") will thus complete before the 2nd thread (probably "t1")'s run() method is entered.
To test the synchronization effects:
The best experiment to run will be to fill the run() method with a call to
Thread.sleep(1000);
Then run your code with, and without the "synchronized" keyword, and time the programs execution .
The output of this code is getting intermixing of thread1 and thread0
package oopd;
/**
*
* #author mani deepak
*/
public class Oopd {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Deepak d,d1;
d=new Deepak();
d1=new Deepak();
Thread t,t1;
t=new Thread(d);
t1=new Thread(d1);
t.start();
t1.start();
}
}
class Deepak implements Runnable
{
#Override
public synchronized void run()
{
String s=Thread.currentThread().getName();
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
System.out.println(s+" "+i);
}
}
}