I have a class with name Socket that have tow function for example func1 and func2
fucn1() {
while(true) {
...
}
}
fucn2() {
while(true) {
...
}
}
I want two of them run with thread in a time and concurrently. how can i do that??
class socket implement Runnable {
public void run() {
func1();
func2();
}
}
In this code only first function is executed not second. How can i do for concurrently run both of them?
My Suggestion is :
Instead of making socket Class Runnable,
Create two Runnable threads as in my example below and call your functions from there. And start these two threads from your Socket class.
class Socket{
private void startThreads() {
new Thread(new Th1()).start();
new Thread(new Th2()).start();
}
}
class Th1 implements Runnable {
#Override
public void run() {
fucn1();
}
}
class Th2 implements Runnable {
#Override
public void run() {
fucn2();
}
}
You can run them concurrently like this:
// start a thread for func1
Thread t1 = new Thread(new Runnable() {
public void run() {
func1();
}
});
t1.start();
// func2 will run in parallel on the main thread
func2();
t1.join(); // if you want to wait for func1 to finish.
You haven't given any details, so I'm assuming they have no side-effects.
If you want to run the two functions concurrently, spawn two threads and run each function in its own thread.
That's precisely what threads are for.
You need to create two threads for this scenario.
class socket implement runable
{
boolean condition;
public socket(boolean condition){
this.condition = condition;
}
public void run()
{
if(condition == true){
func1();
}else{
func2();
}
}
}
Thread t1 = new Thread(new Socket(true));
Thread t1 = new Thread(new Socket(false));
t1.start();
t2.start();
In addition to this you need to yield control in each method just to make sure that every thread will get fair chance to run.
Related
I have a method called processOutbox. I want it to be thread safe. I don't want another thread to call this method while one thread is at it. I have implemented it the following way. Have I done it correctly? Are there any loopholes in my implementation? If there are any, then please advice on how I can resolve it.
this.start();
outboxLock.lock();
timer = new Timer();
try{
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
processOutbox();
}
}, 0, period);
} finally{
outboxLock.unlock();
}
If you want to make your method processOutbox, you should use the keyword synchronized:
public class YourClass{
public synchronized void processOutbox(){
//do all you want
}
}
More info at:https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
If in your code you have an instance of YourClass called for example myInstance , all calls to processOutbox() will be thread safe because they will be locked at instance level.
For example:
YourClass myInstance = new YourClass();
Thread thread1 = new Thread(){
public void run(){
myInstance.processOutbox();
}
}
Thread thread2 = new Thread(){
public void run(){
myInstance.processOutbox();
}
}
thread1.start();
thread2.start();
Here thead2 will be waiting until thread1 finishes the call to "processOutbox"
But for example:
YourClass myInstance = new YourClass();
YourClass myInstance2= new YourClass();
Thread thread1 = new Thread(){
#Override
public void run(){
myInstance.processOutbox();
}
};
Thread thread2 = new Thread(){
#Override
public void run(){
myInstance2.processOutbox();
}
}
thread1.start();
thread2.start();
thead2 will NOT wait because they are calling the method on different instances.
Someone specifically asked about using ReentrantLock -- So I'm adding that response on to this one, because this one is correct.
public class YourClass {
private Lock outboxLock = new ReentrantLock();
public void processOutbox() {
outboxLock.lock()
try {
// do stuff
} finally {
outboxLock.unlock()
}
}
}
I mention this specifically because you can also do things, where you keep other threads out of the lock without causing them to block by using tryLock instead.
public class YourClass {
private Lock outboxLock = new ReentrantLock();
public void processOutbox() {
if( outboxLock.tryLock() ) {
try {
// do stuff
} finally {
outboxLock.unlock()
}
}
}
}
Use a CountDownLatch for synchronization.
Consider the code :
public class MyThread implements Runnable{
private volatile static boolean running = true;
public void stopThread()
{
running = false;
}
#Override
public void run() {
while (running)
{
try {
System.out.println("Sleeping ...");
Thread.sleep(15000);
System.out.println("Done sleeping ...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
MyThread thread = new MyThread();
thread.run();
}
}
Is it possible to stop a thread that implements Runnable with a boolean , without extending Thread ?
Is it possible to stop a thread that implements Runnable
A class that implements Runnable is not a thread. It is just a plain class with no magic to it, declaring a single void run() method. Your example therefore doesn't start any threads.
So instead of misleadingly naming your class MyThread, you should name it MyTask and pass it to a Thread constructor:
final MyTask task = new MyTask();
new Thread(task).start();
Thread.sleep(2000);
task.stopRunning(); // renamed from stopThread
Also, do make the running flag an instance variable. Each MyTask should have its own running flag.
MyThread myt = new MyThread();
(new Thread(myt)).start();
Later call
myt.stopThread();
Sounds like you want to use the built in interrupt mechanism which does basically the same thing you're trying to implement.
public class MyRunnable implements Runnable{
#Override
public void run() {
while (!Thread.interrupted())
{
try {
System.out.println("Sleeping ...");
Thread.sleep(15000);
System.out.println("Done sleeping ...");
} catch (InterruptedException e) {
// This means someone called thread.interrupt() while you were sleeping
return;
}
}
}
public static void main(String[] args)
{
// You didn't extend Thread, you implemented Runnable:
Thread thread = new Thread(new MyRunnable());
// thread.run() is synchronous, for this (the main) thread to continue use:
thread.start();
...
thread.interrupt();
}
}
Yes, you can. The Runnable code you have above is almost correct, but you should probably make the running field not static. The way you create your Thread needs an extra step, though. It should be:
Runnable r = new MyThread(); // MyThread already implements Runnable instead of extending Thread, so that's correct.
Thread t = new Thread(r);
t.start(); // not t.run() or r.run(), that would execute the code synchronously
r.stopThread(); // when needed
For this below program, the ans is --> print : printName , then wait for 5 seconds then print : printValue
But as far as I know that its up to JVM to pick a thread and start its run method. So why it cannot be (printvalue printname and then 5 sec pause).
Note : I understand the conept of synchornized method but how we are sure here that JVM will always pick the thread t1 as its first thread.
class B {
public synchronized void printName() {
try {
System.out.println("printName");
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
}
}
public synchronized void printValue() {
System.out.println("printValue");
}
}
public class Test1 extends Thread {
B b = new B();
public static void main(String argv[]) throws Exception {
Test1 t = new Test1();
Thread t1 = new Thread(t, "t1");
Thread t2 = new Thread(t, "t2");
t1.start();
t2.start();
}
public void run() {
if (Thread.currentThread().getName().equals("t1")) {
b.printName();
} else {
b.printValue();
}
}
}
In this context, the synchronize just means that they can't run at the same time, not that they have to run in order. If you want them to run in order, then you don't want threads, or you want a more sophisticated queuing mechanism.
So, you are correct in that the it could either be "printName" pause "printValue" or "printValue" "printName" pause.
If you run the program multiple times, you'll likely see the first one more frequently. You will see the second output occasionally. The skew is because there is a slight delay between the start() on thread 1 and start() on thread 2.
how we are sure here that JVM will always pick the thread t1 as its first thread.
You can never be sure that the t1 thread will start running before the t2 thread starts running. If you need the t1 thread to do something before the t2 thread does some other thing, then you will have to use some synchronization object (e.g., a Semaphore) to make t2 wait.
Semaphore semaphore = new Semaphore(0);
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
doTheThingThatHasToBeDoneFirst();
semaphore.release();
doOtherStuff();
}
}).start();
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
semaphore.acquire(); //will not return until t1 thread calls release().
doOtherOtherStuff();
}
}).start();
But that is not really a smart way to use threads. Why not just do this instead?
doTheThingThatHasToBeDoneFirst();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
doOtherStuff();
}
}).start();
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
doOtherOtherStuff();
}
}).start();
As a rule of thumb, the more synchronization you have between your threads, the less benefit you get from using threads. If you want certain things to happen in a certain order, you should do those things in that order in a single thread.
The trick to using threads is to design your program so that there are useful things it can do where order does not matter.
I want to know the best way how to notify another thread. For example, I have a background thread:
public void StartBackgroundThread(){
new Thread(new Runnable() {
#Override
public void run() {
//Do something big...
//THEN HOW TO NOTIFY MAIN THREAD?
}
}).start();
}
When it finished it has to notify main thread? If somebody knows the best way how to do this I'll appreciate it!
The typical answer is a BlockingQueue. Both BackgroundThread (often called the Producer) and MainThread (often called the Consumer) share a single instance of the queue (perhaps they get it when they are instantiated). BackgroundThread calls queue.put(message) each time it has a new message and MainThread calls 'queue.take()which will block until there's a message to receive. You can get fancy with timeouts and peeking but typically people want aBlockingQueueinstance such asArrayBlockingQueue`.
Purely based on your question you could do this:
public class test
{
Object syncObj = new Object();
public static void main(String args[])
{
new test();
}
public test()
{
startBackgroundThread();
System.out.println("Main thread waiting...");
try
{
synchronized(syncObj)
{
syncObj.wait();
}
}
catch(InterruptedException ie) { }
System.out.println("Main thread exiting...");
}
public void startBackgroundThread()
{
(new Thread(new Runnable()
{
#Override
public void run()
{
//Do something big...
System.out.println("Background Thread doing something big...");
//THEN HOW TO NOTIFY MAIN THREAD?
synchronized(syncObj)
{
System.out.println("Background Thread notifing...");
syncObj.notify();
}
System.out.println("Background Thread exiting...");
}
})).start();
}
}
and see this output
PS C:\Users\java> javac test.java
PS C:\Users\java> java test
Main thread waiting...
Background Thread doing something big...
Background Thread notifing...
Background Thread exiting...
Main thread exiting...
Just call notify()
public void run() {
try {
while ( true ) {
putMessage();
sleep( 1000 );
}
}
catch( InterruptedException e ) { }
}
private synchronized void putMessage() throws InterruptedException {
while ( messages.size() == MAXQUEUE )
wait();
messages.addElement( new java.util.Date().toString() );
notify();
}
You can't "notify the main thread".
The best approach is to use an ExecutorService, like this for example:
import java.util.concurrent.*;
// in main thread
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(new Runnable() {
#Override
public void run() {
//Do something big...
}
});
future.get(); // blocks until the Runnable finishes
The classes are written specially to deal with asynchronous operations, and all the code in there is already written for you and bullet-proof.
Edit
If you don't want to block the main thread while waiting, wait within another thread:
final Future<?> future = executorService.submit(new Runnable() {
#Override
public void run() {
//Do something big...
}
});
new Thread(new Runnable() {
#Override
public void run() {
future.get(); // blocks until the other Runnable finishes
// Do something after the other runnable completes
}
}).start();
One thread notifying another thread is not a good way to do it. Its better to have 1 master thread that gives the slave thread work. The slave thread is always running and waits until it receives work. I recommend that you draw two columns and determine exactly where each thread needs to wait.
public void run()
{
//Do something big...
synchronized(this)
{
done = true;
}
}
Java includes libraries that make this really easy see ExecutorService and the following post
Producer/Consumer threads using a Queue
Not sure sure if I am doing this right. I need to make a new thread to write out message certain number of times. I think this works so far but not sure if its the best way of doing it. Then i need to display another message after thread has finished running. How do I do that ? Using isAlive() ? How do i implement that ?
public class MyThread extends Thread {
public void run() {
int i = 0;
while (i < 10) {
System.out.println("hi");
i++;
}
}
public static void main(String[] args) {
String n = Thread.currentThread().getName();
System.out.println(n);
Thread t = new MyThread();
t.start();
}
}
Till now you are on track. Now, to display another message, when this thread has finished, you can invoke Thread#join on this thread from your main thread. You would also need to handle InterruptedException, when you use t.join method.
Then your main thread will continue, when your thread t has finished. So, continue your main thread like this: -
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Your Message");
When your call t.join in a particular thread (here, main thread), then that thread will continue its further execution, only when the thread t has completed its execution.
Extending the Thread class itself is generally not a good practice.
You should create an implementation of the Runnable interface as follows:
public class MyRunnable implements Runnable {
public void run() {
//your code here
}
}
And pass an intance of it to the thread as follows:
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
Please check this answer here on SO: Implementing Runnable vs. extending Thread
This is how you can do that.........
class A implements Runnable
{
public void run()
{
for(int i=1;i<=10;i++)
System.out.println(Thread.currentThread().getName()+"\t"+i+" hi");
}
}
class join1
{
public static void main(String args[])throws Exception
{
A a=new A();
Thread t1=new Thread(a,"abhi");
t1.start();
t1.join();
System.out.println("hello this is me");//the message u want to display
}
}
see join() details on
join