How Join method work in Thread. If write join method in run method then its going to deadloack. Just need to information why its happening.
Code Snipet:
public class ThreadSchuduling extends Thread{
static ThreadSchuduling threadObj3;
public ThreadSchuduling(){
System.out.println("Default Constructor");
}
public ThreadSchuduling(String name){
System.out.println("Parameter Constructor");
}
public void run(){
try{
threadObj3.join();
}catch(Exception e){
System.out.println("Error in RUN "+e);
}
System.out.println(Thread.currentThread().getName());
for(int i = 0; i < 10; i++){
System.out.println("Value is = "+i);
}
}
public static void main(String[] args) {
ThreadSchuduling threadObj1 = new ThreadSchuduling("Thread1");
ThreadSchuduling threadObj2 = new ThreadSchuduling("Thread2");
threadObj3 = new ThreadSchuduling("Thread3");
ThreadSchuduling threadObj4 = new ThreadSchuduling("Thread4");
threadObj1.start();
threadObj2.start();
threadObj3.start();
System.out.println("Thread 3 is started");
threadObj4.start();
try{
threadObj3.join();
}catch(Exception e){
System.out.println("Errpr "+e);
}
System.out.println("Main Method completed");
}
}
I just want to complete the thread3 before the thread1 and thread2
You haven't explained what threadObj3 is... is that a reference to the same thread? If so, it's understandable that it will deadlock - it's waiting until it's finished, which it won't do because it's waiting!
What are you actually trying to achieve?
OMG,threadObj3 is always waiting by itself,if you want to complete thread3 before thread1 and thread2, you can set the priority,or it's hard to make sure thread3's execution before other thread.
Related
I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively.
Wanted to know if the approach for using wait() and notify() is correct?
Main Class
public class MyMain {
public static void main(String[] args) {
MyThread1 obj = new MyThread1();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);
thread1.setName("t1");
thread2.setName("t2");
thread1.start();
thread2.start();
}
}
Thread Class
public class MyThread1 implements Runnable{
int i = 0;
#Override
public synchronized void run() {
while(i<10)
{
if(i%2==0)
{
try{
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();
}catch(Exception e){ e.printStackTrace(); }
}else
{
try{
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();
}catch(Exception e){ e.printStackTrace(); }
}
}
}
}
Can there be a better usage of wait() and notify() instead of using it in both the if conditions?
Since there you have some code repetition I'd just go with something like:
while(true) {
//If it's not my turn I'll wait.
if(i%2==0) wait();
// If I've reached this point is because:
// 1 it was my turn OR 2 someone waked me up (because it's my turn)
System.out.println(Thread.currentThread()": "+i);
i++; // Now is the other thread's turn
// So we wake him up
notify();
}
Also, be very careful with monitor's behaviour. (Thread waiting/notifying queues).
//The below code is throwing illegalmonitorstate exception.
public class Multithreading implements Runnable {
static int i=0;
public boolean ist1=true;
public boolean ist2=false;
public static void main (String args[]){
Multithreading ins= new Multithreading();
Thread t1 =new Thread(ins);
Thread t2 =new Thread(ins);
t1.setName("Even");
t2.setName("ODD");
t1.start();
t2.start();
}
#Override
// Wanted to right run method used by two threads to print
// even and odd number in sequence
public void run() {
while(i<=9){
try{
if(Thread.currentThread().getName().contains("Even")&& i%2==0){
System.out.println(Thread.currentThread().getName()+"________"+i);
i=i+1;
Thread.currentThread().wait(100);
}
// due to wait is not used with synchronized but
// i am not able to correct it
if(Thread.currentThread().getName().contains("ODD") && i%2>=1){
System.out.println(Thread.currentThread().getName()+"________"+i);
i=i+1;
Thread.currentThread().wait(100);
//System.out.println(e);
}
}catch(Exception e){
System.out.println(e);
}
}
}
}
To pause a thread, you need to use Thread.sleep() in your case instead of wait().
I have two thread classes: one that prints numbers from 0 to 9, and another from 100 to 109. What I want is to make the first thread wait for the other one to finish. For this, I used the join() method, but it's not working. Please tell me where I'm going wrong:
//demonstrates the use of join() to wait for another thread to finish
class AThread implements Runnable {
Thread t;
AThread() {
t = new Thread(this);
}
public void run() {
try {
for (int i=0; i<10; i++) {
System.out.println(i);
Thread.sleep(10);
}
} catch (InterruptedException e) {
System.out.println(t + " interruped.");
}
}
public void halt(Thread th) {
try {
th.join();
} catch (InterruptedException e) {
System.out.println(t + " interruped.");
}
}
}
//a different thread class (we distinguish threads by their output)
class BThread implements Runnable {
Thread t;
BThread() {
t = new Thread(this);
}
public void run() {
try {
for (int i=100; i<110; i++) {
System.out.println(i);
Thread.sleep(10);
}
} catch (InterruptedException e) {
System.out.println(t + " interruped.");
}
}
}
public class WaitForThread {
public static void main(String[] args) {
AThread t1 = new AThread();
BThread t2 = new BThread();
t1.t.start();
t1.halt(t2.t); //wait for the 100-109 thread to finish
t2.t.start();
}
}
You call join on the thread before it has started. That doesn't work; in that case, join will return immediately, it's not going to wait until the other thread has started and stopped later. You can see this in the API documentation:
Thread.join()
This implementation uses a loop of this.wait calls conditioned on this.isAlive.
Thread.isAlive()
Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
Reorder the statements in your main method
t1.t.start();
t2.t.start();
t1.halt(t2.t); //wait for the 100-109 thread to finish
edit to answer your questions in the comments:
If you want the thread in AThread to wait for the thread in BThread to finish before doing its job, then you'll need to call join in AThread.run, and change your main method:
class AThread implements Runnable {
Thread t;
Thread threadToWaitFor;
AThread(Thread threadToWaitFor) {
t = new Thread(this);
this.threadToWaitFor = threadToWaitFor;
}
public void run() {
// First wait for the other thread to finish
threadToWaitFor.join();
// ...
}
// ...
}
public class WaitForThread {
public static void main(String[] args) {
BThread t2 = new BThread();
AThread t1 = new AThread(t2.t);
t2.t.start();
t1.t.start();
}
}
i need help, i try to use synchronization thread in java but it can't run...
i have two class with thread like this
for(int j=0;j<idW.length;j++){
webtext = d.getWebText(idW[j]);
ThreadPrepo tpo =new ThreadPrepo(webtext, host[j%jumhost], "server", 1099,idW[j]);
Thread t1=new Thread(tpo);
t1.start();
}
//thread untuk setfitur tanpa rmi
int ukuran=idW.length;
ProsesSetfitur pro=new ProsesSetfitur(idW);
Thread t2=new Thread(pro);
t2.start();
this is the code in class threadprepo :
public class ThreadPrepo implements Runnable{
String host,server,c,webtext;
int port,idweb;
DataDB db=new DataDB();
public ThreadPrepo(String webtext,String host,String server,int port,int idweb){
this.webtext=webtext;
this.host=host;
this.server=server;
this.port=port;
this.idweb=idweb;
}
#Override
public void run(){
preponi();
}
public synchronized void preponi(){
try{
System.out.println("hostnya :"+host);
Registry reg=LocateRegistry.getRegistry(host,port);
Sportrmijob rmi=(Sportrmijob) reg.lookup("server");
rmi.SetInput(webtext);
List l=rmi.getresult();
String[] hasilprep=new String[l.size()];
for(int k=0;k<l.size();k++){
hasilprep[k]=l.get(k).toString();
}
db.insertWordney(idweb, hasilprep);
String [][] frekdb=db.getFrekDB(idweb);
db.doinsertfrek(idweb,frekdb);
}
catch(Exception e){
System.out.println("error di class threadprepo "+e.getMessage());
}
}
}
and then this is code in class prosesSetFitur
public class ProsesSetfitur implements Runnable{
DataDB d=new DataDB();
int []idweb;
public ProsesSetfitur(int[]idweb){
this.idweb=idweb;
}
#Override
public void run(){
try{
Thread.sleep(500);
setfitur();
}
catch(Exception e){
System.out.println("error setfitur "+e.getMessage());
}
}
public synchronized void setfitur() throws InterruptedException{
System.out.println("(proses setfitur)");
String []allkata;
String fitur;
String []fiturs=new String[15];
String []kata_kata=new String[15];
System.out.println("nilai iD="+idweb.length);
for(int s=0;s<idweb.length;s++){
//System.out.println("IDWEEEEEEEEEEB"+idweb[s]);
allkata=d.getUrutanKata(idweb[s]);
for(int u=0;u<15;u++){
// System.out.println("PERULANGAN U KE"+u);
if(u<=4){
fitur="T";
//System.out.println("kata ke" +u+" = "+allkata[u]+" fiturnya = "+fitur);
kata_kata[u]=allkata[u];
fiturs[u]=fitur;
}
else if(u>4&&u<10){
fitur="S";
//System.out.println("kata ke"+u+" = "+allkata[u]+" fiturnya = "+fitur);
kata_kata[u]=allkata[u];
fiturs[u]=fitur;
}
else if(u>=10&&u<15){
fitur="R" ;
//System.out.println("kata ke"+u+" = "+allkata[u]+" fiturnya = "+fitur);
kata_kata[u]=allkata[u];
fiturs[u]=fitur;
}
}
d.insertfitur(idweb[s], kata_kata, fiturs);
}
}
can anyone give me solution to solve this problem...why thread in class ProsesSetFitur is execute first?how synchronization thread can work?please help...
public void run(){
try{
Thread.sleep(500);
setfitur();
}
run() method called only once when you start a thread. Again for different thread run() method will be different and call only once for the thread.
Also your preponi() and setfitur() called single time from run(). thats why you should not put synchronized modifier before preponi() and setfitur().
you should use synchronized when multiple thread access same resource or same function or same code block to make it thread safe.
Thread []tArray=new Thread[idW.length];
for(int j=0;j<idW.length;j++)
{
webtext = d.getWebText(idW[j]);
ThreadPrepo tpo =new ThreadPrepo(webtext, host[j%jumhost], "server", 1099,idW[j]);
tArray[j]=new Thread(tpo);
tArray[j].start();
tArray[j].join();
}
//thread untuk setfitur tanpa rmi
int ukuran=idW.length;
ProsesSetfitur pro=new ProsesSetfitur(idW);
Thread t2=new Thread(pro);
t2.start();
A thread sleep may be a pragmatic solution but it is not a guarantee for thread synchronization. To coordinate thread actions you should go for the basic wait/notify pattern whereas the threads uses conditions to perform certain actions. For a good introduction read this articles.
http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
http://www.journaldev.com/1037/java-thread-wait-notify-and-notifyall-example
Consider the following code :-
public class UsingWait1{
public static void main(String... aaa){
CalculateSeries r = new CalculateSeries();
Thread t = new Thread(r);
t.start();
synchronized(r){
try{
r.wait(); //Here I am waiting on an object which is Runnable. So from its run method, it can notify me (from inside a synchronized block).
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
System.out.println(r.total);
try{
Thread.sleep(1);
} catch (InterruptedException e){
System.out.println("Interrupted");
}
System.out.println(r.total);
}
}
class CalculateSeries implements Runnable{
int total;
public void run(){
synchronized(this){
for(int i = 1; i <= 10000; i++){
total += i;
}
notify(); // Line 1 .. Notify Exactly one of all the threads waiting on this instance of the class to wake up
}
}
}
Here I am waiting on CalculateSeries which is Runnable. So I can notify the waiting thread from the run() method of CalculateSeries.
But now, consider the following code where I am waiting on an object which is not Runnable.
public class WaitNotOnThread{
public static void main(String... aaa){
NotRunnable nr = new NotRunnable();
IAmRunnable r = new IAmRunnable(nr);
new Thread(r).start();
synchronized(nr){
try{
nr.wait();
} catch(InterruptedException e){
System.out.println("Wait interrupted");
}
System.out.println("After being notified within synchronized");
}
System.out.println("After synchronized");
}
}
class IAmRunnable implements Runnable{
NotRunnable nr;
IAmRunnable(NotRunnable nr){
this.nr = nr;
}
public void run(){
synchronized(nr){
try{
Thread.sleep(1000);
} catch(InterruptedException e){
System.out.println("Sleeping Interrupted :( ");
}
notify(); // Line 2
}
}
}
class NotRunnable{
}
Here I get an IllegalMonitorStateException at Line 2. I am waiting on the same instance of the object (which is not Runnable) while calling both, wait() as well as notify(). Then what is the problem?
Can someone also give some scenarios where it would be useful to wait on an object which is not Runnable??
Wait need not be on Runnable. That is why notify() is on Object and not on Runnable. I guess that helps in all cases we want to avoid busy wait.
The problem seems to be the synchronized() is on nr, and the notify is called on different object. Also synchronized should be on final variables.
class IAmRunnable implements Runnable {
final NotRunnable nr;
IAmRunnable( final NotRunnable nr) {
this.nr = nr;
}
public void run() {
synchronized (nr) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Sleeping Interrupted :( ");
}
nr.notify(); // Line 2
}
}
}