[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

threads share data

Posted on 2011-04-26
20
Medium Priority
?
330 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.
0
Comment
Question by:gudii9
  • 9
  • 8
  • 3
20 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35471376


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

0
 
LVL 7

Author Comment

by:gudii9
ID: 35471474
any better examples. please advise
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35471495
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

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Assisted Solution

by:objects
objects earned 400 total points
ID: 35471512
0
 
LVL 7

Author Comment

by:gudii9
ID: 35750822
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
0
 
LVL 7

Author Comment

by:gudii9
ID: 35750863
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;
}
}
0
 
LVL 7

Author Comment

by:gudii9
ID: 35750878
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.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750883
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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750898
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

0
 
LVL 92

Expert Comment

by:objects
ID: 35751079
> i have gone through link.Did not understood this example. please advise


which bit did you not understand
0
 
LVL 92

Expert Comment

by:objects
ID: 35774099
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
0
 
LVL 7

Author Comment

by:gudii9
ID: 35891204
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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35891471
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
0
 
LVL 7

Author Comment

by:gudii9
ID: 36005397
>>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
0
 
LVL 7

Author Comment

by:gudii9
ID: 36005407
aopweb is webproject though. is that is reason that project is not showing up?
0
 
LVL 7

Author Comment

by:gudii9
ID: 36005414
i was able to run few other java programs from same project, same package same src location. not sure why it wont run now.
0
 
LVL 47

Accepted Solution

by:
for_yan earned 1600 total points
ID: 36005575

I think if you go to Run --> Run Configurations and then in the left column
double-click Appliaction and then it will open window where in the upper
choice - you should be able to choose project and in the lower should be able to slecet
the class whicvh have main method inside that project
I think after you once run it this way you can right-click the project and it will give the choice runa as application


0
 
LVL 7

Author Comment

by:gudii9
ID: 36012155
>>>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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36012165
Probably it is simpler just to create a separate small project for this code
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36012182
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
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month18 days, 23 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question