I need a variable to count upwards but in increments of 2 seconds. Right now I'm simply using a ++; function, but as you know it's extremely fast.
Is there anything simple I can use to count at a slower pace?
Thread.sleep(2000);
This will make your program to wait for 2 seconds between this method call and whatever line of execution immediately follows this.
public class Count implements Runnable{
public void run(){
for(int i=0;i<=6;i+=2){
Thread.sleep(2000)//in milliseconds ...sleeping for 2 sec
sysout(...);//print your value
}
}
}
Start it this way
Runnable r=new Count();
Thread t=new Thread(r);
t.start(); // start the thread
What you doing is basicly making a thread and running with a delay.I hope you get a concept
Yes, you can pause the execution for two seconds by using Thread.sleep(2000).
//Your code...
Thread.sleep(2000);
counter = counter + 2;
//Your code...
This will print from 1 to 99, incrementing by 2 with a one second pause between increments.
public static void main(String[] args) {
for (int i = 1; i < 100; i += 2) { // i = i + 2
System.out.printf("i = %d\n", i); // print i = #
try {
Thread.sleep(2000); // two seconds.
} catch (InterruptedException e) {
}
}
}
Related
I have a simple concurrent code that increments a shared variable.
Two threads increment the counter 10,000,000 times each and print the result.
It works alright (race condition is resolved with synchronized inside the increment method).
However after thread A is done incrementing, thread B starts incrementing before thread A has a chance to prints its result (should be 10,000,000). I can resolve it by getting thread B to sleep 3 seconds before starting its own increment:
public class DogLatch {
private static Counter counter = new Counter();
public static void main(String[] args) throws Exception {
Thread a = new Thread(new A());
Thread b = new Thread(new B());
a.start();
b.start();
a.join();
b.join();
System.out.printf("counter: %,d", counter.getValue());
}
static class Counter {
private int i;
public void increment() {
synchronized (this) {
i++;
}
}
public int getValue() {return i;}
public void setValue(int i ) {this.i = i;}
}
static class A implements Runnable {
#Override
public void run() {
for (int i = 0; i < 10_000_000; i++) {
counter.increment();
}
System.out.println("A done: " + counter.getValue());
}
}
static class B implements Runnable {
#Override
public void run() {
System.out.println("Go to school");
System.out.println("Walk dog");
try {
Thread.sleep(5000);
}
catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < 10_000_000; i++) {
counter.increment();
}
System.out.println("B done: " + counter.getValue());
}
}
}
would print
Go to school
Walk dog
A done: 10000000
B done: 20000000
counter: 20,000,000
However if I repalce B with:
static class B implements Runnable {
#Override
public void run() {
System.out.println("Go to school");
System.out.println("Walk dog");
for (int i = 0; i < 10_000_000; i++) {
counter.increment();
}
System.out.println("B done: " + counter.getValue());
}
}
I get
Go to school
Walk dog
A done: 17368068
B done: 20000000
counter: 20,000,000
output. Is there a way to achieve the correct output where A done: 10000000 and B done: 10000000 is displayed, without resorting to Thread.sleep() in B?
Actually, your program is not really doing much concurrent processing. You wait 5 seconds in thread B while thread A increments up to 10,000,000 and then B wakes up and continues.
This would be the result if you just started them one after the other in a single thread.
But you know it's working fine since the the end result is always 20,000,000 without the sleep statement.
If you force alternation you will loose the benefit of using threads. The fact that A prints out different values but the final tally is 20,000,000 is indicative of it working perfectly!
I work in the multithreading problem where 2 threads are started from the main. The code is provided below,
package com.multi;
public class App {
private int count = 0;
public void doWork() {
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count is: " + count);
}
public static void main(String[] args) {
App worker = new App();
worker.doWork();
}
}
In the book, it informs that there is a possibility that the count value can be printed less than 20000 in some cases. They provided some explanation but even after reading for few times, I was unable to comprehend that completely. Like there is a try block that join the threads and that meant to ensure to complete both for loops.
a. In which circumstances, the count can be printed less than the 20000 and why both of the threads won't increase the count value?
b. If I wrote like
private volatile int count = 0;
private AtomicInteger count = 0;
will these essentially solve the issue?
Consider this sequence
count is 1
thread1 reads count 1 into local var x
thread2 reads count 1 into local var y
thread1 increments x to 2
thread1 writes x value 2 to count
thread2 increments y to 2
thread2 writes the y value 2 to count
When you do count++, it is a read from the field count, an addition of 1 to the value, and then a write of the result back to the field count, so my example sequence is essentially what can happen in your code.
In my example sequence, even though the field was incremented twice, the count is just 2, and not 3.
This happens because both threads are reading and writing from the same field at the same time.
I am trying to simulate a 100 m running race program in java using multithreading. In this attempt I made a Atomic integer variable which should be common to all threads. This variable should increase by 1 after each thread crosses 100. unfortunately the result is not as expected.This is my attempt at the program.
package running;
import java.util.concurrent.atomic.*;
public class Employee implements Runnable{
AtomicInteger j = new AtomicInteger();
public void run() {
for(int i=1;i<=100;i++){
System.out.println(Thread.currentThread().getName()+" " + i);
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if(i==100)
{
System.out.println(Thread.currentThread().getName()+" is in "+j.incrementAndGet()+" place");
}
}
}
public static void main(String []args) throws Exception{
Employee e= new Employee();
Thread a= new Thread(e,"First");
Thread b= new Thread(e,"Second");
Thread c= new Thread(e,"Third");
Thread d= new Thread(e,"Fourth");
Thread f= new Thread(e,"Fifth");
a.start();
b.start();
c.start();
d.start();
f.start();
}
}
To demonstrate my problem in an understandable way I have added a print statement to check the running of the threads in the code . Here is the last 10 lines of the output.
Second 100
Fourth 100
Third 100
Fifth 100
First 100
Fourth is in 3 place
Third is in 1 place
Second is in 2 place
Fifth is in 4 place
First is in 5 place
I don't see unexpected results. when I run your code I get:
First is in 1 place
Third is in 3 place
Second is in 4 place
Fifth is in 2 place
Fourth is in 5 place
if I run the code again, I get this:
First is in 1 place
Second is in 2 place
Fifth is in 4 place
Fourth is in 3 place
Third is in 5 place
as expected, the results are not always the same. and the AtomicInteger is not losing any update.
if you want the results to be displayed in order, you need to synchronize the part of the code that registers the results. (to make sure that the first thread that reaches 100 will write that information before the next thread reaches 100) for example, see below:
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
public class Employee implements Runnable {
private static AtomicInteger j = new AtomicInteger();
private static Queue<String> queue = new ArrayDeque<>();
public static void main(String[] args) throws Exception {
Employee e = new Employee();
Thread a = new Thread(e, "First");
Thread b = new Thread(e, "Second");
Thread c = new Thread(e, "Third");
Thread d = new Thread(e, "Fourth");
Thread f = new Thread(e, "Fifth");
a.start();
b.start();
c.start();
d.start();
f.start();
a.join();
b.join();
c.join();
d.join();
f.join();
while (queue.size() > 0) {
System.out.println(queue.remove());
}
}
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (queue) {
if (i == 100) {
queue.add(Thread.currentThread().getName() + " is in " + j.incrementAndGet() + " place");
}
}
}
}
}
I want to know how I can solve the following problem:
I have created multiple threads of the same kind. They are all have a run-method with a timed while-loop and a synchronized-block, in which wait() is called first, then notify(). This results in all threads staying in wait()-state and none of them calling notify().
How can I overcome this deadlock-situation? Is there a solution using wait()/notify()?
public class Deadlock3 implements Runnable {
LinkedList<Integer> intList;
public Deadlock3(LinkedList<Integer> list) {
intList = list;
new Thread(this).start();
}
public void run() {
long startTime = System.currentTimeMillis();
try {
while (System.currentTimeMillis() - startTime < 10) {
synchronized (intList) {
Integer number = intList.removeFirst();
System.out.println(number + " removed");
number = (number + 3) % 21;
intList.addLast(number);
System.out.println(Thread.currentThread().getName()+" - "+number + " added");
intList.wait();
intList.notifyAll();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 20; i++) {
list.add(i);
}
for (Integer i : list) {
System.out.println(i);
}
for (int i = 0; i < 4; i++) {
new Deadlock3(list);
}
}
}
Thanks for your answers...
How can I overcome this deadlock-situation? Is there a solution using wait()/notify()?
Let's take a look at your code. You start 4 threads by calling new Thread(this).start(); in the constructor of Deadlock3. That's a really bad pattern by the way because the thread can start using the fields before the object has been fully constructed. It is better to do:
for (int i = 0; i < 4; i++) {
new Thread(new Deadlock3(list)).start();
}
But that's not the problem. When the Deadlock3 starts, the first thread synchronizes on intList, does some counting and stuff, and calls intList.wait(). This waits until someone calls intList.notify() or notifyAll(). The first thread goes to sleep waiting and releases the intList lock. The problem is that each thread goes through the same process. They all are waiting on intList and no one reaches the notifyAll().
The real question is what is the point of calling wait() and notify? As I see it you don't need them and they can be removed. If you need them, please explain why?
When I remove those lines and run the program finishes after spitting out a bunch of the following cycles:
...
18 removed
Thread-3 - 0 added
19 removed
Thread-3 - 1 added
20 removed
Thread-3 - 2 added
0 removed
Thread-3 - 3 added
1 removed
Thread-3 - 4 added
2 removed
...
Hope this helps.
Hi all I have this code:
public class ThreadTester {
public static void main(String args[]) {
Counter c = new Counter();
for (int i = 0; i < 10; i++) {
MyThread a = new MyThread(c);
MyThread b = new MyThread(c);
a.start();
b.start();
}
System.out.println("The value of the balance is " + c.getVal());
}
}
class MyThread extends Thread {
private Counter c;
public MyThread(Counter c){ this.c = c; }
public void run(){ s.increment(); }
}
class Counter {
private int i = 100;
public synchronized void increment(){ i++; }
public synchronized int getVal(){ return i; }
}
Now I thought that this should give the desired result of 120 - however the result seems to fluctuate between 115 and 120. If I add a Thread.sleep(1) after b.start() I always get the desired result of 120. Why does this happen?
It's really been confusing me and I'd appreciate any help I could get, Thanks
You're printing the value of the counter after having started all the threads, and not after all the threads have completed.
Use Thread.join() on all the threads you have started to wait until they've completed, and then print the value. Or use a CountDownLatch. Sleeping gives you the correct result by accident. It allows all the threads to complete, but only because they have so few things to do that sleeping for 1 millisecond is sufficient.
Because threads run in parallel.
You're printing c.getVal() in the main thread before one or more of your other threads has incremented it.
When you sleep, you're allowing the other threads enough time to complete, then printing.
Because not all the threads have completed their increment task by the time you get to the System.out. Injecting the sleep allows the threads to finish before getting to the output.
The reason:
The third Thread (which executes the main()) function gets to the following statement right after starting Threads a and b in random order and that's why you get unpredictable results.
System.out.println("The value of the balance is " + c.getVal());
Next Question:
If I add a Thread.sleep(1) after b.start() I always get the desired result of 120. Why does this happen?
This happens because you stop the main Thread long enough (1 second is a long time in CPU world) to allow Threads a and b to finish.
Solution: Make the main Thread wait until both Threads a and b have finished. One way:
Counter c = new Counter();
for (int i = 0; i < 10; i++) {
MyThread a = new MyThread(c);
MyThread b = new MyThread(c);
a.start();
b.start();
}
a.join(); // wait for thread a to finish
b.join(); // wait for thread b to finish
System.out.println("The value of the balance is " + c.getVal());
You are printing the result potentially before the threads are finished (which is why the results vary). You need to wait until all threads have completed before printing the result.
Restructure your main method as follows:
public static void main(String args[]) {
Counter c = new Counter();
MyThread[] a = MyThread[20];
for (int i = 0; i < 20; i++) {
a[i] = new MyThread(c);
a[i].start();
}
for (int i = 0; i < 20; i++) {
a[i].join();
}
System.out.println("The value of the balance is " + c.getVal());
}
Firstly, I am looping 20 times since your loop iterated 10 times whilst creating two threads (so you were creating 20 threads too). You need to hold on to the references (via the a array) so that the main thread can wait until all the threads have completed (with join). When they have all completed, the correct result is returned.