Changing an arrays elements with thread
I need the change the elements of an array by using a thread. It should change (add or sub an integer number) an element randomly, sleep for 2 sec and change another one randomly.
So i created my array and my thread, but I don't know how to change it.
public static void main(String args) {
int myarray= new int[5];
Thread x= new Thread();
x.start();
try
{
x.sleep(2000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
public class myThread implements Runnable {
public myThread(){ //an empty constructor, to pass parameters
}
public void run(){
}
public void update(){ //i tohught i could use that for changing elements
}
java arrays multithreading
add a comment |
I need the change the elements of an array by using a thread. It should change (add or sub an integer number) an element randomly, sleep for 2 sec and change another one randomly.
So i created my array and my thread, but I don't know how to change it.
public static void main(String args) {
int myarray= new int[5];
Thread x= new Thread();
x.start();
try
{
x.sleep(2000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
public class myThread implements Runnable {
public myThread(){ //an empty constructor, to pass parameters
}
public void run(){
}
public void update(){ //i tohught i could use that for changing elements
}
java arrays multithreading
1
Unrelated:x.sleep(2000)
is bad code. Methodsleep
isstatic
, so should be called by qualifying with the class name, not with an instance value, so it should beThread.sleep(2000)
– Andreas
Jan 1 at 21:43
You need to pass the array into the thread as a parameter to the constructor. Also, you need to actually use themyThread
class. Note that Java naming convention is for class names to start with uppercase letter, so it should be calledMyThread
.
– Andreas
Jan 1 at 21:45
add a comment |
I need the change the elements of an array by using a thread. It should change (add or sub an integer number) an element randomly, sleep for 2 sec and change another one randomly.
So i created my array and my thread, but I don't know how to change it.
public static void main(String args) {
int myarray= new int[5];
Thread x= new Thread();
x.start();
try
{
x.sleep(2000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
public class myThread implements Runnable {
public myThread(){ //an empty constructor, to pass parameters
}
public void run(){
}
public void update(){ //i tohught i could use that for changing elements
}
java arrays multithreading
I need the change the elements of an array by using a thread. It should change (add or sub an integer number) an element randomly, sleep for 2 sec and change another one randomly.
So i created my array and my thread, but I don't know how to change it.
public static void main(String args) {
int myarray= new int[5];
Thread x= new Thread();
x.start();
try
{
x.sleep(2000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
public class myThread implements Runnable {
public myThread(){ //an empty constructor, to pass parameters
}
public void run(){
}
public void update(){ //i tohught i could use that for changing elements
}
java arrays multithreading
java arrays multithreading
edited Jan 1 at 22:16
Paul Rooney
12.7k72845
12.7k72845
asked Jan 1 at 21:34


sadclownsadclown
1
1
1
Unrelated:x.sleep(2000)
is bad code. Methodsleep
isstatic
, so should be called by qualifying with the class name, not with an instance value, so it should beThread.sleep(2000)
– Andreas
Jan 1 at 21:43
You need to pass the array into the thread as a parameter to the constructor. Also, you need to actually use themyThread
class. Note that Java naming convention is for class names to start with uppercase letter, so it should be calledMyThread
.
– Andreas
Jan 1 at 21:45
add a comment |
1
Unrelated:x.sleep(2000)
is bad code. Methodsleep
isstatic
, so should be called by qualifying with the class name, not with an instance value, so it should beThread.sleep(2000)
– Andreas
Jan 1 at 21:43
You need to pass the array into the thread as a parameter to the constructor. Also, you need to actually use themyThread
class. Note that Java naming convention is for class names to start with uppercase letter, so it should be calledMyThread
.
– Andreas
Jan 1 at 21:45
1
1
Unrelated:
x.sleep(2000)
is bad code. Method sleep
is static
, so should be called by qualifying with the class name, not with an instance value, so it should be Thread.sleep(2000)
– Andreas
Jan 1 at 21:43
Unrelated:
x.sleep(2000)
is bad code. Method sleep
is static
, so should be called by qualifying with the class name, not with an instance value, so it should be Thread.sleep(2000)
– Andreas
Jan 1 at 21:43
You need to pass the array into the thread as a parameter to the constructor. Also, you need to actually use the
myThread
class. Note that Java naming convention is for class names to start with uppercase letter, so it should be called MyThread
.– Andreas
Jan 1 at 21:45
You need to pass the array into the thread as a parameter to the constructor. Also, you need to actually use the
myThread
class. Note that Java naming convention is for class names to start with uppercase letter, so it should be called MyThread
.– Andreas
Jan 1 at 21:45
add a comment |
1 Answer
1
active
oldest
votes
First, you have to create an class declaration, that accepts required arr
and implements run()
method with logic.
public static class MyThread implements Runnable {
private final int arr;
private final Random random = new Random();
private MyThread(int arr) {
this.arr = arr;
}
@Override
public void run() {
try {
while (true) {
// wait for 2 seconds
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
// randomly choose array element
int i = random.nextInt(arr.length);
// randomly choose increment or decrement an elements
boolean add = random.nextBoolean();
// lock WHOLE array for modification
synchronized (arr) {
arr[i] = add ? arr[i] + 1 : arr[i] - 1;
}
}
} catch(InterruptedException e) {
}
}
}
Second, you have to create an array and required number of threads for modifications.
// create an array
int arr = new int[5];
// create threads and start
for (int i = 0; i < 20; i++)
new Thread(new MyThread(arr)).start();
That's all basically. Sure, it is possible to not lock whole array to modify only one elements, but this is another story.
The finalprintln(...)
call in your main routine can be executed while worker threads still are running. Not that anybody would be able to tell by examining the program's output, but still... Are you sure that's what you wanted to show?
– Solomon Slow
Jan 1 at 23:36
I dont understand why output is [0, 0, 0, 0, 0]
– sadclown
Jan 1 at 23:50
Wait until all threads will be stopped
– oleg.cherednik
Jan 1 at 23:51
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53999117%2fchanging-an-arrays-elements-with-thread%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
First, you have to create an class declaration, that accepts required arr
and implements run()
method with logic.
public static class MyThread implements Runnable {
private final int arr;
private final Random random = new Random();
private MyThread(int arr) {
this.arr = arr;
}
@Override
public void run() {
try {
while (true) {
// wait for 2 seconds
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
// randomly choose array element
int i = random.nextInt(arr.length);
// randomly choose increment or decrement an elements
boolean add = random.nextBoolean();
// lock WHOLE array for modification
synchronized (arr) {
arr[i] = add ? arr[i] + 1 : arr[i] - 1;
}
}
} catch(InterruptedException e) {
}
}
}
Second, you have to create an array and required number of threads for modifications.
// create an array
int arr = new int[5];
// create threads and start
for (int i = 0; i < 20; i++)
new Thread(new MyThread(arr)).start();
That's all basically. Sure, it is possible to not lock whole array to modify only one elements, but this is another story.
The finalprintln(...)
call in your main routine can be executed while worker threads still are running. Not that anybody would be able to tell by examining the program's output, but still... Are you sure that's what you wanted to show?
– Solomon Slow
Jan 1 at 23:36
I dont understand why output is [0, 0, 0, 0, 0]
– sadclown
Jan 1 at 23:50
Wait until all threads will be stopped
– oleg.cherednik
Jan 1 at 23:51
add a comment |
First, you have to create an class declaration, that accepts required arr
and implements run()
method with logic.
public static class MyThread implements Runnable {
private final int arr;
private final Random random = new Random();
private MyThread(int arr) {
this.arr = arr;
}
@Override
public void run() {
try {
while (true) {
// wait for 2 seconds
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
// randomly choose array element
int i = random.nextInt(arr.length);
// randomly choose increment or decrement an elements
boolean add = random.nextBoolean();
// lock WHOLE array for modification
synchronized (arr) {
arr[i] = add ? arr[i] + 1 : arr[i] - 1;
}
}
} catch(InterruptedException e) {
}
}
}
Second, you have to create an array and required number of threads for modifications.
// create an array
int arr = new int[5];
// create threads and start
for (int i = 0; i < 20; i++)
new Thread(new MyThread(arr)).start();
That's all basically. Sure, it is possible to not lock whole array to modify only one elements, but this is another story.
The finalprintln(...)
call in your main routine can be executed while worker threads still are running. Not that anybody would be able to tell by examining the program's output, but still... Are you sure that's what you wanted to show?
– Solomon Slow
Jan 1 at 23:36
I dont understand why output is [0, 0, 0, 0, 0]
– sadclown
Jan 1 at 23:50
Wait until all threads will be stopped
– oleg.cherednik
Jan 1 at 23:51
add a comment |
First, you have to create an class declaration, that accepts required arr
and implements run()
method with logic.
public static class MyThread implements Runnable {
private final int arr;
private final Random random = new Random();
private MyThread(int arr) {
this.arr = arr;
}
@Override
public void run() {
try {
while (true) {
// wait for 2 seconds
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
// randomly choose array element
int i = random.nextInt(arr.length);
// randomly choose increment or decrement an elements
boolean add = random.nextBoolean();
// lock WHOLE array for modification
synchronized (arr) {
arr[i] = add ? arr[i] + 1 : arr[i] - 1;
}
}
} catch(InterruptedException e) {
}
}
}
Second, you have to create an array and required number of threads for modifications.
// create an array
int arr = new int[5];
// create threads and start
for (int i = 0; i < 20; i++)
new Thread(new MyThread(arr)).start();
That's all basically. Sure, it is possible to not lock whole array to modify only one elements, but this is another story.
First, you have to create an class declaration, that accepts required arr
and implements run()
method with logic.
public static class MyThread implements Runnable {
private final int arr;
private final Random random = new Random();
private MyThread(int arr) {
this.arr = arr;
}
@Override
public void run() {
try {
while (true) {
// wait for 2 seconds
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
// randomly choose array element
int i = random.nextInt(arr.length);
// randomly choose increment or decrement an elements
boolean add = random.nextBoolean();
// lock WHOLE array for modification
synchronized (arr) {
arr[i] = add ? arr[i] + 1 : arr[i] - 1;
}
}
} catch(InterruptedException e) {
}
}
}
Second, you have to create an array and required number of threads for modifications.
// create an array
int arr = new int[5];
// create threads and start
for (int i = 0; i < 20; i++)
new Thread(new MyThread(arr)).start();
That's all basically. Sure, it is possible to not lock whole array to modify only one elements, but this is another story.
edited Jan 1 at 23:37
answered Jan 1 at 21:54
oleg.cherednikoleg.cherednik
7,16021119
7,16021119
The finalprintln(...)
call in your main routine can be executed while worker threads still are running. Not that anybody would be able to tell by examining the program's output, but still... Are you sure that's what you wanted to show?
– Solomon Slow
Jan 1 at 23:36
I dont understand why output is [0, 0, 0, 0, 0]
– sadclown
Jan 1 at 23:50
Wait until all threads will be stopped
– oleg.cherednik
Jan 1 at 23:51
add a comment |
The finalprintln(...)
call in your main routine can be executed while worker threads still are running. Not that anybody would be able to tell by examining the program's output, but still... Are you sure that's what you wanted to show?
– Solomon Slow
Jan 1 at 23:36
I dont understand why output is [0, 0, 0, 0, 0]
– sadclown
Jan 1 at 23:50
Wait until all threads will be stopped
– oleg.cherednik
Jan 1 at 23:51
The final
println(...)
call in your main routine can be executed while worker threads still are running. Not that anybody would be able to tell by examining the program's output, but still... Are you sure that's what you wanted to show?– Solomon Slow
Jan 1 at 23:36
The final
println(...)
call in your main routine can be executed while worker threads still are running. Not that anybody would be able to tell by examining the program's output, but still... Are you sure that's what you wanted to show?– Solomon Slow
Jan 1 at 23:36
I dont understand why output is [0, 0, 0, 0, 0]
– sadclown
Jan 1 at 23:50
I dont understand why output is [0, 0, 0, 0, 0]
– sadclown
Jan 1 at 23:50
Wait until all threads will be stopped
– oleg.cherednik
Jan 1 at 23:51
Wait until all threads will be stopped
– oleg.cherednik
Jan 1 at 23:51
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53999117%2fchanging-an-arrays-elements-with-thread%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Unrelated:
x.sleep(2000)
is bad code. Methodsleep
isstatic
, so should be called by qualifying with the class name, not with an instance value, so it should beThread.sleep(2000)
– Andreas
Jan 1 at 21:43
You need to pass the array into the thread as a parameter to the constructor. Also, you need to actually use the
myThread
class. Note that Java naming convention is for class names to start with uppercase letter, so it should be calledMyThread
.– Andreas
Jan 1 at 21:45