I have been having trouble with getting my timer to show my bar graph updating itself over time instead, what I have is my graph being sorted automatically even though I set the timer to update every couple of seconds.
Here are my paint and updatetextfieldthread method.
private class Display extends JPanel {
private Color color = Color.RED;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
Dimension d = getPreferredSize();
int clientWidth = d.width;
int clientHeight = d.height;
int barWidth = clientWidth / array.length;
int x=0, y=0;
int base=410;
for(int i=0;i<array.length;i++){
x+=30;
y+=30;
int linethickness=20;
int linelength=50;
g.setColor(Color.red);
g.fillRect(x, base-linelength*array[i], linethickness , linelength*array[i]);
g.setColor(Color.black);
g.drawRect(x, base-linelength*array[i], linethickness, linelength*array[i]);
}
}
}
private class UpdateTextFieldThread extends SwingWorker<Void, Integer>
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
#Override
public void run() {
insertionSort(array);
display.repaint();
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES);
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
return null;
}
protected void process(java.util.List<Integer> list)
{
textfield.setText("" + list.get(list.size() - 1));
}
}
now revised: I'm breaking down my sorting method step by step and I am updating the thread inside of it but it is still not breaking down my graph.
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
if (src == button1){
int[] array2=array;
for (int i = 1; i < array2.length; i++) {
int thingToInsert = array2[i];
int j = i - 1;
while (j >= 0 && thingToInsert<array2[j]) {
array2[j+1] = array2[j];
j--;
}
array2[j+1] = thingToInsert;
(new UpdateTextFieldThread()).execute();
}
}
}
}
private class UpdateTextFieldThread extends SwingWorker<Void, Integer>
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
ExecutorService service = Executors.newSingleThreadExecuto();
try {
Runnable r = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(THREAD_DELAY);
display.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES);
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
return null;
}
Related
I don't see any problem with this code, but the result doesn't display in the console window in eclipse.
What's the problem?
class Buffer{
private int data;
private boolean empty = true;
public synchronized int get() {
while(empty) {
try {
wait();
} catch (InterruptedException e) {
}
}
empty = true;
notifyAll();
return data;
}
public synchronized void put(int data) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
}
}
empty = false;
this.data = data;
notifyAll();
}
}
class Producer implements Runnable{
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
for (int i=0; i<0; i++) {
buffer.put(i);
System.out.println("Producer: " + i + "th cake produced.");
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
class Consumer implements Runnable{
private Buffer buffer;
public Consumer(Buffer drop) {
this.buffer = drop;
}
public void run() {
for(int i=0; i<10; i++) {
int data = buffer.get();
System.out.println("Consumer: " + data + "th cake comsumed.");
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
Buffer buffer = new Buffer();
(new Thread(new Producer(buffer))).start();
(new Thread(new Consumer(buffer))).start();
}
}
In the run() method of the producer you have bad for loop
for (int i=0; i<0; i++)
but it should be
for (int i=0; i<10; i++)
That was probably a typo :)
I have just started learning threads and pretty new to it.I'm trying to print alphabets and numbers one after the other.I have synchronized them using a flag but of no use.
public class Alphabets {
public static void main(String[] args) {
AN an= new AN(false);
Thread t1=new Thread(new Runnable() {
#Override
public void run() {
try {
an.Alpha();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2= new Thread(new Runnable() {
#Override
public void run() {
try {
an.numbers();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
...
class AN
{
boolean flag;
AN(boolean flag)
{
this.flag=flag;
}
synchronized void Alpha() throws InterruptedException
{
if(flag==false)
{
for(char i='A'; i<='Z';i++)
{
System.out.println(+i);
notifyAll();
flag=true;
}
}
else
{
wait();
}
}
synchronized void numbers() throws InterruptedException
{
if(flag==true)
{
for(int i=1;i<=26;i++)
{
System.out.println(+i);
notifyAll();
flag=false;
}
}
else
{
wait();
}
}
}
My desired output is : a1b2c3d4....
My console output is : abcd...1234...
Can anybody point out the mistake since I'm unable to synchronize these two threads.
Change class AN to check the flag in while loop.
public class AN {
boolean flag;
AN(boolean flag) {
this.flag = flag;
}
synchronized void Alpha() throws InterruptedException {
for(char i = 'A'; i <= 'Z'; i++) {
while(flag == true) {
wait();
}
System.out.println(i);
notifyAll();
flag = true;
}
}
synchronized void numbers() throws InterruptedException {
for(int i = 1; i <= 26; i++) {
while(flag == false) {
wait();
}
System.out.println(i);
notifyAll();
flag = false;
}
}
Well, what you want is more or less pipelining, therefore the threads need to know when they are allowed to work.
I'd therefore use a Queue to await the input on one thread and wait for it to be set in the other thread.
Class AN:
import java.util.concurrent.BlockingQueue;
class AN
{
BlockingQueue<Boolean> input;
BlockingQueue<Boolean> output;
AN(BlockingQueue<Boolean> input, BlockingQueue<Boolean> output)
{
this.input = input;
this.output = output;
}
void Alpha() throws InterruptedException
{
for (char i = 'a'; i <= 'z'; i++) {
input.take();
System.out.print(i);
output.put(Boolean.TRUE);
}
}
void numbers() throws InterruptedException
{
for (int i = 1; i <= 26; i++) {
input.take();
System.out.print(i);
output.put(Boolean.TRUE);
}
}
}
Class Test (or where your main is):
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
BlockingQueue<Boolean> input = new LinkedBlockingQueue<>();
BlockingQueue<Boolean> output = new LinkedBlockingQueue<>();
AN an1 = new AN(output, input);
AN an2 = new AN(input, output);
output.add(Boolean.TRUE);
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
try {
an1.Alpha();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable()
{
#Override
public void run()
{
try {
an2.numbers();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
Outputs: a1b2c3d4e5f6g7h8i9j10k11l12m13n14o15p16q17r18s19t20u21v22w23x24y25z26
You can achieve this by using BlockingQueue and Object's wait and notify methods.
public class AlphaNum {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
AtomicBoolean flag = new AtomicBoolean(Boolean.TRUE);
Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
try {
for(int i=1;i<=26;i++){
synchronized (lock){
while (flag.get()){
lock.wait();
}
System.out.print(i);
flag.set(Boolean.TRUE);
lock.notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
try {
for(char c='A';c<='Z';c++){
synchronized (lock){
while (!flag.get()){
lock.wait();
}
System.out.print(c);
flag.set(Boolean.FALSE);
lock.notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
The above code prints a1b2c3d4.......z26
There are many ways to achieve this, Below one is one of them.
package interview;
public class TestAplhaAndNumberPrinterThreads {
// created object as static so we can access print method of this class from thread's run methods
public static TestAplhaAndNumberPrinterThreads output = new TestAplhaAndNumberPrinterThreads();
private final Object syncer = new Object();
private int state = 0;
public void print(char character) throws InterruptedException {
synchronized (syncer) {
while (true) {
if (state == 0) {
System.out.print(character + ", ");
state = 1;
syncer.notify();
return;
} else {
syncer.wait();
}
}
}
}
public void print(int number) throws InterruptedException {
synchronized (syncer) {
while (true) {
if (state == 1) {
System.out.print(number + ", ");
state = 0;
syncer.notify();
return;
} else {
syncer.wait();
}
}
}
}
public static void main(String[] args) {
NumberPrinter numberPrinter = new NumberPrinter();
AlphabetsPrinter alphabetsPrinter = new AlphabetsPrinter();
numberPrinter.start();
alphabetsPrinter.start();
}
}
class NumberPrinter extends Thread {
#Override
public void run() {
try {
for (int i = 1; i <= 26; i++) {
TestAplhaAndNumberPrinterThreads.output.print(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class AlphabetsPrinter extends Thread {
#Override
public void run() {
try {
for (char i = 'a'; i <= 'z'; i++) {
TestAplhaAndNumberPrinterThreads.output.print(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// output: a, 1, b, 2, c, 3, d, 4, e, 5, f, 6, g, 7, h, 8, i, 9, j, 10, k, 11, l, 12, m, 13, n, 14, o, 15, p, 16, q, 17, r, 18, s, 19, t, 20, u, 21, v, 22, w, 23, x, 24, y, 25, z, 26,
I think the big things is for you to know, how to use break points to debug in IDE and why your code was not working. You can see the process of your code will run. I have post the picture at the last and this code which will work like your wish
class AN {
boolean flag;
AN(boolean flag) {
this.flag = flag;
}
synchronized void Alpha() throws InterruptedException {
if (flag == false) {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.println(i);
flag = true;
notify();
wait();
}
}
}
synchronized void numbers() throws InterruptedException {
if (flag == true) {
for (int i = 1; i <= 26; i++) {
System.out.println(+i);
flag = false;
notify();
wait();
}
}
}
}
enter image description here
I want to create new Runnable in a loop. However, it is not possible to use a variable within an inner class. I cannot use global/instance variable because it generates wrong results. My program is similar to the simplified code that follows:
public class RunManager {
public void runManager(int delay, final Context context) {
for (int dim = 7; dim < 227; dim++) {
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
the error is: Variable 'dim' is accessed from within inner class, needs to be declared final.
Your problem is you're trying to access a non final variable from a new thread. In order for variable to ne accesed from new thread it needs to be declared as final. In your cas you can just copy the dim int to a final int array of size 1 then access the array from thread.
Probably the most legible way of doing it would be to create a constructor for your Runnable which accepts an int as parameter. Such as:
public class MyRunnable implements Runnable {
public MyRunnable(Context context, int dim) {
// save parameters as class variables
}
public void run() {
// do the work
}
}
Then call it:
Runnable r = new MyRunnable(context, dim);
new Thread(r).start();
You should use final int[] dim if you want to have access to the value within inner class.
public class RunManager {
public void runManager(int delay, final Context context) {
for (final int dim[] = {7}; dim[1] < 227; dim[1]++) {
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, dim[1]);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Option 2 - use field:
public class RunManager {
private int _dim;
public void runManager(int delay, final Context context) {
for (int dim = 7; dim < 227; dim++) {
_dim = dim;
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, _dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Option 3 - iterate in another method and add final int dim as method argument:
private void createThreads(int delay, final Object context) {
for (int dim = 7; dim < 227; dim++) {
runManager(delay, context, dim);
}
}
public void runManager(int delay, final Context context, final int dim) {
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Option 4 - use custom runnable. You can implement class as recommended by #BMacedo or create abstract class and implement logic in inner class.
public class RunManager {
public void runManager(int delay, final Context context) {
for (int dim = 7; dim < 227; dim++) {
CustomRunnable r = new CustomRunnable() {
private int _dim;
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, _dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
public void setDim(int dim) {
_dim = dim;
}
};
r.setDim(dim);
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
abstract class CustomRunnable implements Runnable {
public abstract void setDim(int dim);
}
}
I am trying execute two jobs simultaneously. One of the things that I am trying to do is displaying a count up timer and the other one is moving the ball.
This is where I create the timer and also call the moveBall method
button.addChangeListener(new ChangeListener() {
int start = 0;
public void stateChanged(ChangeEvent e) {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
timeValue.setText(++start + " sec");
}
};
timer = new Timer(1000, taskPerformer);
timer.start();
ball.moveBall();
}
});
This is my moveBall method
public void moveBall() {
Thread ball = new Thread() {
double counter = 0;
int t = (int) (2 * Vy / 9.8);
public void run() {
try {
while (t >= 0) {
// calculate Vx and Vy
Ball.this.setX(Ball.this.getX() + Vx);
Ball.this.setY(Ball.this.getY() - Vy);
counter += 50;
if (counter == 1000) {
t--;
counter = 0;
}
paintingComponent.repaint();
Thread.sleep(20);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ball.start();
}
When I execute the above code the label for displaying the time passed is not changing at all during the ball is moving and when the movement is over it takes the last number that it supposed to take.
This is a example two executions of two threads, Java simultaneous execution
public class ThreadExecutor extends Thread {
private String name;
private int executionCount;
public ThreadExecutor(final String name, final int executionCount) {
this.name = name;
this.executionCount = executionCount;
}
#Override
public void run() {
int count = 1;
while (count <= executionCount) {
System.out.println("Executing thread ".concat(name).concat(" : ") + count);
count++;
}
}
}
public class Main {
public static void main(String args[]) {
final ThreadExecutor one = new ThreadExecutor("One", 1);
final ThreadExecutor two = new ThreadExecutor("Two", 2);
one.start();
two.start();
}
}
I have a program that loads slowly, which I guess is due to the amount of image resources I have to load at the beginning. I thought multi-threading would help, but now I'm not so sure. Here is my automatic multi-threading method.
private static Thread[] t;
private static int currentThreads;
public static void loadWithThreads(Object[] array, IntegerRunnable r) {
final int threads = Runtime.getRuntime().availableProcessors();
t = new Thread[threads];
for (int i = 0; i < threads; i ++) {
t[i] = new Thread("HMediaConverter") {
final int id = currentThreads;
int items = (array.length / threads) * currentThreads;
#Override
public void run() {
super.run();
for (int i = items; i < (items + (array.length / threads)); i ++) {
r.run(i);
}
//Recycle this thread so it can be used for another time.
try {
t[id].join();
lock.notifyAll();
currentThreads --;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t[i].setPriority(Thread.MAX_PRIORITY);
t[i].start();
currentThreads ++;
}
}
And here is my image loading code:
public static ImageIcon loadImageIcon(String path) {
return new ImageIcon(ImageIO.read(Tools.class.getClassLoader().getResource(path));
}
Surely there is a way to speed things up? I'm running this on a perfectly good Intel i5, it shouldn't be this slow, so it must be my code.
Loading 113 images of a total of 159.14mb with...
public static void loadWithoutThreads(File[] array) {
for (File file : array) {
try {
ImageIO.read(file);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Took ~15s
With...
public static void loadWithThreads(File[] array) {
final int threads = Runtime.getRuntime().availableProcessors();
t = new Thread[threads];
CountDownLatch latch = new CountDownLatch(threads);
for (int i = 0; i < threads; i++) {
t[i] = new Thread("HMediaConverter") {
final int id = currentThreads;
int items = (array.length / threads) * currentThreads;
#Override
public void run() {
try {
System.out.println("Starting " + id);
for (int i = items; i < (items + (array.length / threads)); i++) {
try {
System.out.println(i + ": " + array[i]);
ImageIO.read(array[i]);
} catch (IOException ex) {
ex.printStackTrace();
}
}
} finally {
latch.countDown();
}
}
};
t[i].setPriority(Thread.MAX_PRIORITY);
System.out.println("Start " + i);
t[i].start();
currentThreads++;
}
try {
latch.await();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
took ~11s
With...
public static void loadWithExecutor(File[] images) {
ExecutorService service = Executors.newFixedThreadPool(2);
List<ImageLoadingTask> tasks = new ArrayList<>(images.length);
for (File file : images) {
tasks.add(new ImageLoadingTask(file));
}
try {
List<Future<BufferedImage>> results = service.invokeAll(tasks);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
service.shutdown();
}
public static class ImageLoadingTask implements Callable<BufferedImage> {
private File file;
public ImageLoadingTask(File file) {
this.file = file;
}
#Override
public BufferedImage call() throws Exception {
return ImageIO.read(file);
}
}
Took ~7s
The ExecutorService is more efficient because when one thread is processing a larger file, the other can be processing a number of small files. This is achieved by pooling the threads that aren't doing any work until they are needed, allowing a thread to perform a lot of short work, while the other thread(s) are also busy. You don't need to wait as long
Have a look at Executors for more details
The following is a re-write that should work that is close to what the op wrote. A re-write into A fixed-size thread pool would probably be better.
//import java.util.concurrent.atomic.AtomicInteger;
private static Thread[] t;
private static AtomicInteger completedLoads = new AtomicInteger(0);
public static void loadWithThreads(Object[] array, IntegerRunnable r) {
final int threads = Runtime.getRuntime().availableProcessors();
t = new Thread[threads];
completedLoads = new AtomicInteger(0);
int targetLoads = array.length;
int itemsPerThread = (array.length / threads);
for (int i = 0; i < threads; i ++) {
t[i] = new Thread("HMediaConverter" + i) {
int startItem = itemsPerThread * i;
#Override
public void run() {
super.run();
for (int i = startItem; i < startItem + itemsPerThread; i ++) {
try {
r.run(i);
}
finally {
completedLoads.incrementAndGet();
}
}
}
};
t[i].setPriority(Thread.MAX_PRIORITY);
t[i].start();
}
// Wait for the images to load
while (completedLoads.get() < targetLoads)
{
try {
Thread.sleep(100);
}
catch (InterruptedException ie) {
// ignore
}
}
}
Isolate which part does the slowing down - e.g by running System.currentTimeMillis() btween major segmnst then show us where is the biggest time - or show us all the program.
Threads handling as noted is questionable and you shouldn't use methods such as join etc out of the box unless you have seen it sometwhere provably working.
So post times and we'll take it from there - it could be the images it could be the threads