I am working on a multi-thread program. Can someone please help me on how to implement the sleep method within my program. I have never used it and the requirement is that the run method uses the sleep method. I did start 4 threads and checked the outlined ranges. and I should Modify the Finder class so its run method utilizes the sleep method. I have never used the sleep method.
import static java.lang.System.out;
class Range
{
int start;
int end;
Range(int s, int e)
{
start = s;
end = e;
}
boolean contains(int x)
{
return end - start >=0;
}
}
class Finder implements Runnable
{
#Override
public void run()
{
}
}
public class ThreadTest implements Runnable
{
static void log(Object o){out.print(o);}
static void logLn(Object o){out.println(o);}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* #see Thread#run()
*/
#Override
public void run()
{
logLn("Running main");
}
static Range myRange = new Range(100, 500);
public static void main(String[] args)
{
if (myRange.contains(300))
{
System.out.println ("You\'re within the correct range.");
}
Finder fc = new Finder();
Thread t1= new Thread(fc);
t1.start();
Thread t2= new Thread(fc);
t2.start();
Thread t3 = new Thread(fc);
t3.start();
Thread t4 = new Thread(fc);
t4.start();
Runnable myRunnable = new Runnable(){
public void run(){
System.out.println("Runnable running");
}
};
myRunnable.run();
}
}
Sleep is a static method provided by the Thread class via Thread.sleep(1000L) where the value you pass is a Long representing milliseconds. Implementing a sleep method doesn't make much sense but calling Thread.sleep() will suspend the current thread that is executing that call.
So my guess is that you are supposed to call Thread.sleep within the run function of Finder.
EDIT
Implementing would simply be calling what I explained:
class Finder implements Runnable{
#Override
public void run(){
System.out.println("Thread " + Thread.currentThread().getId() + " sleeping");
Thread.sleep(1500L);
System.out.println("Thread " + Thread.currentThread().getId() + " awake");
}
}
Related
Im new to Threads and I was wondering how could I define what two or more different Threads do in a Java program. Do i define them all in the same public void run method? If so, how do I do it? I would like the Threat t1 to invoke the increment method, t2 to invoke the decrement method and both of them to call the value method
Here's the code example:
package interference;
/**
*
* #author rodrigopeniche
*/
public class Interference implements Runnable{
/**
* #param args the command line arguments
*
*/
Counter counter1= new Counter();
class Counter{
private int c= 0;
public void increment()
{
c++;
}
public void decrement()
{
c--;
}
public int value()
{
return c;
}
}
public static void main(String[] args) {
// TODO code application logic here
Thread t1= new Thread(new Interference());
Thread t2= new Thread(new Interference());
t1.start();
t2.start();
}
#Override
public void run() {
counter1.increment();
counter1.decrement();
counter1.value();
}
}
You can set names to threads like thread1, thread2. After that, in the run method, check the name of the thread currently running and do the necessary action.
You have to add a while loop inside the run method if you need to run it longer.
public static void main(String[] args) {
Interference interference = new Interference();//create a new Interference object
Thread t1 = new Thread(interference, "thread1");//pass the runnable interference object and set the thread name
Thread t2 = new Thread(interference, "thread2");//pass the runnable interference object and set the thread name
t1.start();
t2.start();
}
#Override
public void run() {
while (true) {//to run it forever to make the difference more visual
String threadName = Thread.currentThread().getName();//get the current thread's name
if (threadName.equals("thread1")) {//if current thread is thread1, increment
counter1.increment();
} else if (threadName.equals("thread2")) {//if current thread is thread2, decrement
counter1.decrement();
}
System.out.println(counter1.value());//print the value
}
}
When you run the code, you can see count is going up and down in a random manner.
In your current code, counter1 is an instance variable of class Interference. You create 2 instances of Interference and then use them to create two Thread objects. When the threads start to run, each Thread is actually working on it's own copy of counter1. I think that may not be what you expect.
package interference;
public class Interference {
static class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new Runnable() {
public void run() {
counter.increment();
System.out.println(counter.value());
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
counter.decrement();
System.out.println(counter.value());
}
});
t1.start();
t2.start();
}
}
I've created a class called Thread that implements Runnable but I cannot invoke the start() or sleep() methods for some reason. Any time I attempt to do so, I get errors saying that these methods are undefined for the class and suggests that I create them. So I created a new project and copied a sample code to see if there was something wrong with my own code and I received the same errors. Here's the sample code:
class Thread implements Runnable {
private int a;
public Thread (int a) {
this.a = a;
}
public void run() {
for (int i = 1; i <= a; ++i) {
System.out.println(Thread.currentThread().getName() + " is " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
and this is my own code:
public class Thread extends PID implements Runnable {
public Thread() {}; // Empty constructor for thread object
public void run() {
Random gen = new Random(); // Generates random values
int sleepTime; // Sleep time
sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
try {
Thread.sleep();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The thread has been terminated");
}
}
To fix your current error, simply rename your Thread class to MyThread (or whatever), because your Thread class is hiding the java.lang.Thread class.
If you want to stick to Thread, you'll have to use the fully qualified name for java.lang.Thread like this:
try{
java.lang.Thread.sleep(1000);
// ...
Mistakes
Change class name from Thread to MyThread.
run() is called when you invoke start(). Invoke start() using class object.
Thread.sleep(); needs an argument say, sleepTime
Here is the code of what I think you want to do. Tested on Eclipse Juno JDK 1.7
import java.util.Random;
class NewThread implements Runnable {
public NewThread () {
}
public void run() {
Random gen = new Random(); // Generates random values
int sleepTime; // Sleep time
sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
try {
Thread.sleep(sleepTime);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The thread has been terminated");
}
}
class MyThread {
public static void main(String[] args) {
NewThread t = new NewThread();
Thread t1 = new Thread(t);
t1.start();
}
}
Output
The thread has been terminated
Interface Runnable do not have methods start() and sleep(), so be carefull with it. Interface Runnable only have run() method, and Java API recommends " the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods."
See Java API's Runnable documentation here: http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html
In every other cases, your class should extned class Thread.
Pardon me if the question sounds silly - I am just starting to use Executor.
I have an existing java app that uses threads in this manner-- basically standalone threads are used--
private Thread spawnThread( )
{
Thread t = new Thread()
{
String taskSnap = task.toString();
public void run()
{
try
{
println( task.run( null ) );
}catch( InterruptedException e )
{
println( "ITC - " + taskSnap + " interrupted " );
}
}
};
return t;
}
As you can see from above, the function returns a new thread.
Now in the main() function of the program, a new thread is created in this manner--
taskThread = spawnThread();
taskThread.start();
What i want to do is, create an executor service (with fixed number of threads)--> and then hand off creation of new thread/execution of task by the new thread to that executor.
As I am very new to Executor, what I wish to know is, how do I change the above code so that instead of a new separate thread being formed, a new thread is instead created within the thread pool. I cannot see any command to create a thread (within the thread pool)--> hand off the above task to that thread (and not to a stand-alone thread as above).
Please let me know how to resolve this problem.
In your main, you can write something like this:
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
executor.submit(new Runnable() {
String taskSnap = task.toString();
public void run() {
try {
println(task.run(null));
} catch( InterruptedException e) {
println("ITC - " + taskSnap + " interrupted ");
}
}
});
The submit method will execute the Runnable on one of the threads within the executor service.
Note: Don't forget to shutdown the executor service when you don't need it any more or it will prevent your program from exiting.
Do your research before asking. The idea is to create a class which implements Runnable and execute it using executor service.
Example from: Java Concurrency (Multithreading) - Tutorial
Implementation of the worker (which implements Runnable):
package de.vogella.concurrency.threadpools;
/** * MyRunnable will count the sum of the number from 1 to the parameter * countUntil and then write the result to the console. * <p> * MyRunnable is the task which will be performed * * #author Lars Vogel * */
public class MyRunnable implements Runnable {
private final long countUntil;
MyRunnable(long countUntil) {
this.countUntil = countUntil;
}
#Override
public void run() {
long sum = 0;
for (long i = 1; i < countUntil; i++) {
sum += i;
}
System.out.println(sum);
}
}
How to use executor service to run trigger the worker thread.
package de.vogella.concurrency.threadpools;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
private static final int NTHREDS = 10;
public static void main(String[] args) {
//You can also use Executors.newSingleThreadExecutor() if you just need 1 thread
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
for (int i = 0; i < 500; i++) {
Runnable worker = new MyRunnable(10000000L + i);
executor.execute(worker);
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue.
executor.shutdown();
// Wait until all threads are finish
//while (!executor.isTerminated()) {
//}
//System.out.println("Finished all threads");
//All the threads might not be finished at this point of time. Thread endtime purely depends on the time taken by the processing logic inside your thread.
}
}
You mean something like this?
class Parallel {
private ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public void shutdown() {
pool.shutdown();
}
public void foo() {
pool.submit(new Runnable() {
#Override
public void run() {
// put your code here
}
});
}
}
Okay, so I've basically done the hardest workaround I could think of for the program that I'm working on and now have everything working....except the program itself.
So, here's the code I'm working with:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
Thread thread = new Thread(new thread2());
public void run() {
thread.start();
double startTime = System.nanoTime();
SortingStuff ss = new SortingStuff();
ss.setVisible(true);
double endTime = System.nanoTime();
double elapsedTime = endTime - startTime;
System.out.println("This operation took " + elapsedTime + " nanoseconds, which is :" + ((elapsedTime / 1000000) / 1000) + " seconds."); // This will be better later
}
});
}
And then the thread2 runnable is something like this:
public static class thread2 implements Runnable{
public void run() {
System.out.println("thread " +Thread.currentThread().getName());
}
Now, if I wanted to call a static method from the thread created, how could I go about doing that? I have a method called "bubbleSort" that I just can't get to work within the created thread. Help?
public static void bubbleSort(final String numbers[], final JButton numButton[]){
//Is the skeleton for the method, however I can't put it in the run area, and I can't seem to access the other thread from outside of where it's run. UGH!
./Frustrated
Running a static method from a class, even one that implements runnable, will not run on that thread, it will run from whichever thread called the static method. Anything that you want to happen in that thread needs to get called from run().
thread2 mythread = new thread2();
new Thread(mythread).start(); //Spawns new thread
thread2.bubbleSort(args); //Runs in this thread, not the spawned one
In response to the comment, I assume you were having problems because you couldn't pass your arguments to the run method. You need to get that data to the thread either before it starts, or through some sort of data stream(file, socket, etc). Here I use the constructor, but it can also be done with a setData(data here) function.
public class Example implements Runnable {
private dataObject args;
public Example(dataObject input) {
args = input;
}
public void dosort(dataObject sortArg){contents}
public void run() {
dosort(args);
}
}
public static void main(stuff) {
Example myExample = new Example(data);
//alternate example
//myExample.setData(data);
new Thread(myExample).start();
}
Can anybody please provide me a good small example demonstrate wait() and notify() functionality in java. I've tried with the below piece of code but it's not showing what i expected.
public class WaitDemo {
int i = 10;
int display() {
System.out.println("Lexmark");
i++;
return i;
}
}
public class ClassDemo1 extends Thread {
private WaitDemo wd = new WaitDemo();
public static void main(String[] args) {
ClassDemo1 cd1 = new ClassDemo1();
ClassDemo1 cd2 = new ClassDemo1();
cd1.setName("Europe");
cd2.setName("America");
cd1.start();
cd2.start();
}
synchronized void display() {
System.out.println("Hello");
notifyAll();
}
public void run() {
synchronized (this) {
try {
{
notify();
System.out.println("The thread is " + currentThread().getName());
wait();
System.out.println("The value is " + wd.display());
}
} catch (InterruptedException e) {
}
}
}
}
The issue is that the method in the class WaitDemo is not getting executed and as per my idea the SOP after wait() should execute. Please help me out on this.
You've got two levels of braces { in your try block. If you remove the inner set (which doesn't appear to do anything), does that fix the problem?
There are several examples around, all of which demonstrate the use. The last link is a set of results that can help you out. If you need more specific things, let me know what it is that your app is trying to do, and I can try to find examples that are more specific to your situation.
http://www.javamex.com/tutorials/wait_notify_how_to.shtml
http://www.java-samples.com/showtutorial.php?tutorialid=306
http://www.coderanch.com/t/234235/threads/java/Wait-Example
https://www.google.com/search?q=wait%28%29+example+java&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
Below is an example of wait & notify in the Object class. The customer is trying to withdraw money of value 2000 but the account is having only 1000 so it has to wait for the deposit. Once the deposit is made, then the customer will be able to withdraw the amount. Until the deposit is made, the customer will be waiting.
class Cust {
private int totalAmount = 1000;
public synchronized void withdrawal(int amount) {
System.out.println("Total amount " + totalAmount + " withdrawing amount " + amount);
while (this.totalAmount < amount) {
System.out.println("not enough amount..waiting for deposit..");
try { wait(); } catch (Exception e) {}
}
this.totalAmount -= amount;
System.out.println("Withdrawal successful.. Remaining balance is "+totalAmount);
}
public synchronized void deposit(int amount){
System.out.println("Depositing amount "+amount);
this.totalAmount += amount;
System.out.println("deposit completed...and Now totalAmount is " + this.totalAmount);
notify();
}
}
class Depo implements Runnable {
Cust c; int depo;
Depo(Cust c, int depo){
this.c = c;
this.depo = depo;
}
#Override
public void run() {
c.deposit(depo);
}
}
class Withdrawal implements Runnable {
Cust c; int with;
Withdrawal(Cust c, int with){
this.c = c;
this.with = with;
}
#Override
public void run() {
c.withdrawal(with);
}
}
public class ObjectWaitExample {
public static void main(String[] args) {
Cust c = new Cust();
Thread w = new Thread(new Withdrawal(c, 2000));
Thread d1 = new Thread(new Depo(c, 50));
Thread d2 = new Thread(new Depo(c, 150));
Thread d3 = new Thread(new Depo(c, 900));
w.start();
d1.start();
d2.start();
d3.start();
}
}
I created two threads one for printing odd numbers (OddThread) and another for even numbers (EvenThread). Inside the run method of each of the threads I used the shared object of class Print to call printOdd() and printEven() for the Odd and EvenThread respectively. I made the shared object of Print static so that only one copy is made. Now synchronizing on the Print object I used a Boolean flag such that when the odd thread printed an odd number it will be sent into the waiting state and the at the same time notifying the even thread to execute. The logic is written in such a way that the odd thread will always print the odd number first no matter what, as the flag is set to false initially preventing the even thread to execute and sending it to a waiting state.
package com.amardeep.test;
public class ThreadDemo {
// Shared object
static Print print = new Print();
public static void main(String[] args) {
new Thread(new OddThread()).start();
new Thread(new EvenThread()).start();
}
}
class EvenThread implements Runnable {
#Override
public void run() {
ThreadDemo.print.printEven();
}
}
class OddThread implements Runnable {
#Override
public void run() {
ThreadDemo.print.printOdd();
}
}
class Print {
public volatile boolean flag = false;
public synchronized void printEven() {
for (int i = 1; i <= 10; i++) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (i % 2 == 0) {
System.out.println("from even " + i);
flag = false;
notifyAll();
}
}
}
}
public synchronized void printOdd() {
for (int i = 1; i <= 10; i++) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (i % 2 != 0) {
System.out.println("from odd " + i);
flag = true;
notifyAll();
}
}
}
}
}
output:-
from odd 1
from even 2
from odd 3
from even 4
from odd 5
from even 6
from odd 7
from even 8
from odd 9
from even 10
Your problem is that you are creating two instances of the Thread class. Thus when the wait() is called, it is on two different instances, neither of which has another thread that is in contention for your monitor, nor is there another thread to call notifyAll() to wake the thread from its wait state.
Thus each thread you have started will wait forever (or until interrupted for some other reason).
You want to have multiple threads accessing the same monitor, so start by trying to code something in which the code in question is not actually a thread, but is simply being used by a thread.
#normalocity has already provided links to multiple examples.
I just updated this answer to include an SCCE.
The workers call pauseIfNeeded on the WorkerPauseManager. If the manager is paused when the worker thread calls pauseIfNeeded(), we call wait(), which tells the calling thread to wait until a different thread calls notify() or notifyAll() on the object being waited on. This happens when the Swing Event Dispatch Thread calls play() on the manager, which in turn calls notifyAll().
Note that you must have a synchronized lock on the object you are calling wait() or notify() on. Since the methods in WorkerPauseManager are synchronized, all the synchronized methods are getting a synchronized lock on the WorkerPauseManager itself.
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* #author sbarnum
*/
public class WorkerPauseManagerTest {
public static void main(String[] args) {
final WorkerPauseManager pauseManager = new WorkerPauseManager();
new Worker("Worker 1", pauseManager).start();
new Worker("Worker 2", pauseManager).start();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JToggleButton playPauseButton = new JToggleButton(new AbstractAction("Pause") {
public void actionPerformed(final ActionEvent e) {
JToggleButton source = (JToggleButton) e.getSource();
if (source.isSelected()) {
pauseManager.start();
source.setText("Pause");
} else {
pauseManager.pause();
source.setText("Play");
}
}
});
playPauseButton.setSelected(true); // already running
JOptionPane.showMessageDialog(null, playPauseButton, "WorkerPauseManager Demo", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
});
}
private static class Worker extends Thread {
final String name;
final WorkerPauseManager pauseManager;
public Worker(final String name, final WorkerPauseManager pauseManager) {
this.name = name;
this.pauseManager = pauseManager;
}
#Override
public void run() {
while (!Thread.interrupted()) {
try {
pauseManager.pauseIfNeeded();
System.out.println(name + " is running");
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public static final class WorkerPauseManager {
private boolean paused;
public synchronized void pauseIfNeeded() throws InterruptedException {
if (paused) wait();
}
public synchronized void pause() {
this.paused = true;
}
public synchronized void start() {
this.paused = false;
notifyAll();
}
}
}
What wait method does is , when some thread executed a synchronized block by locking some object (we call that object is "a") , then inside that synchronized block when the thread executed the wait method of object "a" like this
A a = new A (); // some class object call "a"
synchronized (a){
a.wait ();//exceptions must be handled
}
Then the a object will release and the thread has to go to the wait state until it has been release from that state.
and anothet thread now can use the a object beacause its a release object. so if another thread locked that object and it executed the notify method from that object like
a.notify ()
Then one of a thread of the threads that went to wait state by object "a" can be released from the wait state. Other wise when call the notifyAll then the all the thread objects will release from that state.
/*
* the below program is like
* tread t1 will first run , and it comes to "notify()" method
* there are no threds waiting bcoz this is the first thread.
* so it will not invoke any other threads. next step is "wait()" method
*will be called and the thread t1 in waiting state. next stament
* "System.out.println("The value is ..."+wd.display());" will not be executed
* because thread t1 is in waiting state.
*
* thread t2 will run ,and it comes to "notify()" method ,there is already
* thread t1 is in waiting state ,then it will be invoked.now thread t1 will
* continue execution and it prints the statement "System.out.println("The value is ..."+wd.display())"
* and thread t2 will be in waiting state now.
*
* if you uncomment "notifyAll()" method then, after t1 thread completes its execution
*then immediately "notifyAll()" method will be called,by that time thread t2 is
* already in waiting state , then thread t2 will be invoked and continues execution.
*or
* if any other threadds are in waiting state all those threads will be invoked.
*/
package threadsex;
/**
*
* #author MaheshM
*/
/**
* #param args the command line arguments
*/
public class WaitNotifyNotifyAllDemo implements Runnable {
WaitDemo wd = new WaitDemo();
public static void main(String[] args) {
WaitNotifyNotifyAllDemo cd1 = new WaitNotifyNotifyAllDemo();
Thread t1 = new Thread(cd1);
t1.setName("mahi1");
Thread t2 = new Thread(cd1);
t2.setName("mahi2");
t1.start();
t2.start();
}
#Override
public void run() {
synchronized (this) {
try {
System.out.println("The thread is=" +
Thread.currentThread().getName());
notify();
wait();
System.out.println("The value is ..." + wd.display());
// notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}