We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

threads share data

gudii9
gudii9 asked
on
Medium Priority
338 Views
Last Modified: 2012-05-11
>>Which of the following statements are true?

1)To implement threading in a program you must import the class java.io.Thread
2) The code that actually runs when you start a thread is placed in the run method
3) Threads may share data between one another
4) To start a Thread executing you call the start method and not the run method


Answer

3) Compile time error: class Runt is an abstract class. It can't be instantiated.

The class implements Runnable but does not define the run method.



Answer )

2)The code that actually runs when you start a thread is placed in the run method
3) Threads may share data between one another
4) To start a Thread executing you call the start method and not the run method

You do not need to import any classes as Threading is an integral part of the Java languag




I have not understood above question and answer clearly from link
http://www.jchq.net/certkey/0701certkey.htm 

can threads can share data. What are the practical examples where threads share data.



Any ideas, resources, links, sample code highly appreciated. thanks in advance.
Comment
Watch Question

Awarded 2011
Awarded 2011

Commented:


You can look at the code in this very simple example:
http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java

Youi see that variable "flag" is shared between the main thread where Outer() is executing
and new thread - the inside fo the run() method

Author

Commented:
any better examples. please advise
Awarded 2011
Awarded 2011

Commented:
This also shows how two thereads share boolean varaible done
the firast one did a little bit and started waiting till
the second one fionishes

When second thread is finished it will set done to true
and the first one will leave the sleeping loop
 

Class Outer
     {    
        public static flag = true;
     boolean done;

        Outer()
        {
            new Test().start();
    // calclating something
        while(!done){
    Thread.currentThread().sleep(1000);
}
        } 
        class Test extends Thread
        { 

           public void run()
           {
             while(Outer.flag)
             {
              //do stuff here
             done = true;
             }  
           }
        }

      }

Open in new window

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Author

Commented:
i was trying to run

>>

Class Outer
     {    
        public static flag = true;
     boolean done;

        Outer()
        {
            new Test().start();
    // calclating something
        while(!done){
    Thread.currentThread().sleep(1000);
}
        }
        class Test extends Thread
        {

           public void run()
           {
             while(Outer.flag)
             {
              //do stuff here
             done = true;
             }  
           }
        }

      }



but i could not. no main method. how to execute it to understand beter. please advise

Author

Commented:
i have gone through link.Did not understood this example. please advise















>>

/*
* Main.java
*/

public class Main {
public Main() {
}

public static void main(String[] args) {
BossThread boss = new BossThread();
boss.start();
}
}

The ‘boss’ class normally does a number of things, such as control thread execution logic and the like. It also serves as a common point in my design from which to launch ‘worker’ threads and also create the ‘datastore’ object. The BossThread looks a little like this.

/*
* BossThread.java
*/
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;

public class BossThread extends Thread {
private final ArrayList workers = new ArrayList();
private final DataStore dataStore = new DataStore();
private String threadType; // type of thread operation
private int numWorkersStarted = 0; // started thread counter
private int numThreads = 20; // number of threads to spawn

public BossThread() {
}

public void run() {
try {
threadType="put";
createWorkerThreads();
startWorkerThreads();

threadType="get";
createWorkerThreads();
startWorkerThreads();
} catch (Exception e) {
e.printStackTrace();
}
}

private void createWorkerThreads() throws Exception {
for (int i = 1; i <= numThreads; i++) {
String threadName = threadType + "_WORKER_" + i;
workers.add(new WorkerThread(threadName, dataStore, threadType));
}
}

private void startWorkerThreads() throws Exception {
int threadStartIndex=numWorkersStarted;
for (int i = threadStartIndex; i < numThreads+threadStartIndex; i++) {
WorkerThread worker = (WorkerThread) workers.get(i);
Thread.sleep(250 + (int) (Math.random() * 500));
worker.start();
numWorkersStarted++;
}
}
}

So you can see that early in the piece I instantiate an instance of the DataStore class, which is then passed as a parameter along with some custom fields like threadName and threadType to my WorkerThread class. I'm also using an ArrayList to simplify the organization, creation and starting of worker threads via some private methods.

The WorkerThread class looks like this.

/*
* WorkerThread.java
*/

public class WorkerThread extends Thread {
private DataStore dataStore;
private String threadType;
private String threadName;

public WorkerThread(String threadName, DataStore dataStore, String threadType) {
this.threadName = threadName;
this.dataStore = dataStore;
this.threadType = threadType;
}

public void run() {
if (threadType.equals("put")) putdataStore();
if (threadType.equals("get")) getdataStore();
}

private void putdataStore() {
for (int i = 0; i < 10; i++) {
dataStore.putResponseTime("key",i);
System.out.println(threadName + " put: " + i);
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void getdataStore() {
int val = 0;
for (int i = 0; i < 10; i++) {
value = dataStore.getResponseTime("key");
System.out.println(threadName + " get: " + val);
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

You can see that its constructor gets the instance of the 'datastore' object, which can then call on public methods of the DataStore class such as putdataStore and getdataStore.

Finally, the DataStore class looks like this.

/*
* DataStore.java
*/

import java.util.*;
import java.util.concurrent.*;

public class DataStore {
private Map responseTimes = new ConcurrentHashMap();
private boolean available = false;

public DataStore() {
}

public synchronized void putResponseTime(String key, int val) {
responseTimes.put(key, val);
notifyAll();
}

public synchronized int getResponseTime(String key) {
notifyAll();
int val=-1;
if(responseTimes.containsKey(key)){
val = responseTimes.get(key);
}
return val;
}
}

Author

Commented:
did not understand this part either. please advise

>.

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Awarded 2011
Awarded 2011

Commented:
This snippet was a sketch of the program not the actual program to execurte.
It just emaphasises that the same varibles can be accessed by
duifferent threads like the variable of Outer class flag can be accessed by the
thread. In order to try to run it we need to invent some time taking process
to repllace //do stuff here
Awarded 2011
Awarded 2011

Commented:
Now I modified it - you can execute it and see how it works:

public class Outer
     {
        public static boolean flag = true;
     static boolean done;

        Outer()
        {
            new Test().start();
    // calclating something
        while(!done){
            try{
    Thread.currentThread().sleep(1000);
            }catch(Exception ex ){
                System.out.println(ex.toString());
            }
            System.out.println("finished sleeping!");
}
        }
        class Test extends Thread
        {

           public void run()
           {
             while(Outer.flag)
             {
              for(int j=0; j<100; j++)System.out.println("j: " + j);   
              //do stuff here
             Outer.done = true;
                 break;
             }
           }
        }

         public static void main(String [] args){
             new Outer();
         }

      }

Open in new window


Ouptut:

j: 0
j: 1
j: 2
j: 3
j: 4
j: 5
j: 6
j: 7
j: 8
j: 9
j: 10
j: 11
j: 12
j: 13
j: 14
j: 15
j: 16
j: 17
j: 18
j: 19
j: 20
j: 21
j: 22
j: 23
j: 24
j: 25
j: 26
j: 27
j: 28
j: 29
j: 30
j: 31
j: 32
j: 33
j: 34
j: 35
j: 36
j: 37
j: 38
j: 39
j: 40
j: 41
j: 42
j: 43
j: 44
j: 45
j: 46
j: 47
j: 48
j: 49
j: 50
j: 51
j: 52
j: 53
j: 54
j: 55
j: 56
j: 57
j: 58
j: 59
j: 60
j: 61
j: 62
j: 63
j: 64
j: 65
j: 66
j: 67
j: 68
j: 69
j: 70
j: 71
j: 72
j: 73
j: 74
j: 75
j: 76
j: 77
j: 78
j: 79
j: 80
j: 81
j: 82
j: 83
j: 84
j: 85
j: 86
j: 87
j: 88
j: 89
j: 90
j: 91
j: 92
j: 93
j: 94
j: 95
j: 96
j: 97
j: 98
j: 99
finished sleeping!

Process finished with exit code 0

Open in new window

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> i have gone through link.Did not understood this example. please advise


which bit did you not understand
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
each worker thread is sharing access to the DataStore instance
ie. there are lots of threads all accessing the one instance of DataStore
The DatStore methods are synchronized to ensure only one calls them at a time

Author

Commented:
when i tried to run program

 class Outer
     {
        public static boolean flag = true;
     static boolean done;

        Outer()
        {
            new Test().start();
    // calclating something
        while(!done){
            try{
    Thread.currentThread().sleep(1000);
            }catch(Exception ex ){
                System.out.println(ex.toString());
            }
            System.out.println("finished sleeping!");
}
        }
        public class Test extends Thread
        {

           public void run()
           {
             while(Outer.flag)
             {
              for(int j=0; j<100; j++)System.out.println("j: " + j);  
              //do stuff here
             Outer.done = true;
                 break;
             }
           }
        }

         public static void main(String [] args){
             new Outer();
         }

      }



it does not show option 'run as java application'. not sure why. please advise



thread.jpg
Awarded 2011
Awarded 2011

Commented:
I don't use Run as java Application

What you see seems quite normal to me, you should
select
Run configurations
then it will show you the screen where you
select the project name and the name of the class which
has a main() method which can be run.

Then you click on Run at the bottom of this window.

After you do this way first time, then next time you want to launch this app,
 you go to
Run menu at the very top of your window
and select Run or just initiate the run with
 ctrl-F11 and it will run this program  (this is until you switch to different
project and setup run for another project,
which would become the new default.)


Thie code you pasted works fine for me in this way.


eclipse-run-config.PNG

Author

Commented:
>>select the project name and the name of the class which

i created the both Outer.java and Test.java


class Outer
     {
        public static boolean flag = true;
     static boolean done;

        Outer()
        {
            new Test().start();
    // calclating something
        while(!done){
            try{
    Thread.currentThread().sleep(1000);
            }catch(Exception ex ){
                System.out.println(ex.toString());
            }
            System.out.println("finished sleeping!");
}
        }
        public class Test extends Thread
        {

           public void run()
           {
             while(Outer.flag)
             {
              for(int j=0; j<100; j++)System.out.println("j: " + j);  
              //do stuff here
             Outer.done = true;
                 break;
             }
           }
        }

         public static void main(String [] args){
             new Outer();
         }

      }



inside the default package under src folder of aopweb project . i do not see under run neither outer nor test. i could not even see the aopweb project also. please advise

Author

Commented:
aopweb is webproject though. is that is reason that project is not showing up?

Author

Commented:
i was able to run few other java programs from same project, same package same src location. not sure why it wont run now.
Awarded 2011
Awarded 2011
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Author

Commented:
>>>the left column
double-click Appliaction and then it will open window


on the left i do not see and web applications at all. I see only java application heading there under which there are some plain java classes which i wrote earlier. the current java classes i wrote under webproject called aopweb which is not visible on the left hand side. does web projects are are not visible on left. please advise
Awarded 2011
Awarded 2011

Commented:
Probably it is simpler just to create a separate small project for this code
Awarded 2011
Awarded 2011

Commented:
And that should not be webproject - just regular Java application - that was a stand alone test, which would not mess
with the rest of your code and it would be then no problem executing it
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.