gudii9
asked on
threads share data
>>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.
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.
ASKER
any better examples. please advise
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
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;
}
}
}
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
i was trying to run
>>
Class Outer
{
public static flag = true;
boolean done;
Outer()
{
new Test().start();
// calclating something
while(!done){
Thread.currentThread().sle ep(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
>>
Class Outer
{
public static flag = true;
boolean done;
Outer()
{
new Test().start();
// calclating something
while(!done){
Thread.currentThread().sle
}
}
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
ASKER
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=numWorker sStarted;
for (int i = threadStartIndex; i < numThreads+threadStartInde x; 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(threadN ame + " 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(threadN ame + " 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.containsK ey(key)){
val = responseTimes.get(key);
}
return val;
}
}
>>
/*
* 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=numWorker
for (int i = threadStartIndex; i < numThreads+threadStartInde
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"))
if (threadType.equals("get"))
}
private void putdataStore() {
for (int i = 0; i < 10; i++) {
dataStore.putResponseTime(
System.out.println(threadN
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(
System.out.println(threadN
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.containsK
val = responseTimes.get(key);
}
return val;
}
}
ASKER
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.
>.
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.
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
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
Now I modified it - you can execute it and see how it works:
Ouptut:
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();
}
}
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
> i have gone through link.Did not understood this example. please advise
which bit did you not understand
which bit did you not understand
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
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
ASKER
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().sle ep(1000);
}catch(Exception ex ){
System.out.println(ex.toSt ring());
}
System.out.println("finish ed 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
class Outer
{
public static boolean flag = true;
static boolean done;
Outer()
{
new Test().start();
// calclating something
while(!done){
try{
Thread.currentThread().sle
}catch(Exception ex ){
System.out.println(ex.toSt
}
System.out.println("finish
}
}
public class Test extends Thread
{
public void run()
{
while(Outer.flag)
{
for(int j=0; j<100; j++)System.out.println("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
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
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
ASKER
>>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().sle ep(1000);
}catch(Exception ex ){
System.out.println(ex.toSt ring());
}
System.out.println("finish ed 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
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().sle
}catch(Exception ex ){
System.out.println(ex.toSt
}
System.out.println("finish
}
}
public class Test extends Thread
{
public void run()
{
while(Outer.flag)
{
for(int j=0; j<100; j++)System.out.println("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
ASKER
aopweb is webproject though. is that is reason that project is not showing up?
ASKER
i was able to run few other java programs from same project, same package same src location. not sure why it wont run now.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
>>>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
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
Probably it is simpler just to create a separate small project for this code
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
with the rest of your code and it would be then no problem executing it
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