Creating Multiple Threaded Loops - java

Sorry if this a bit of a basic question but I've been thinking about doing multiple sprite loops and for the first time I tried to create two threads in main, both with while(true) loops. My intention: to have two threads looping simultaneously. However when I run the program it seems to interrupt the flow of execution and the second loop doesn't getting executed in a new thread but just stops with the program stuck on the first endless while() loop of a thread. I think it is still just executing the main thread rather than starting a new one and then continuing on.
I've tried it two ways:
Once with Threads:
public class Zzz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
r1 r = new r1();
r2 a = new r2();
r.start();
a.start();
}
}
public class r1 extends Thread {
#Override
public void start() {
while(true) {
System.out.println("r1");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
}
public class r2 extends Thread {
#Override
public void start() {
while(true) {
System.out.println("r2");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
}
And once with Runnable:
public class Zzz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
r1 r = new r1();
r2 a = new r2();
r.run();
a.run();
}
}
public class r1 implements Runnable {
#Override
public void run() {
while(true) {
System.out.println("r1");
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
}
public class r2 implements Runnable {
#Override
public void run() {
while(true) {
System.out.println("r2");
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
}
But to no avail. It always gets stuck at R1. Any ideas anyone? I've googled and looked around about threads and I can't find this covered anywhere.

You need to override run method & in case of runnable you need to create instance of Thread
public class MyThread extends Thread{
#Override
public void run() {
while(true) {
System.out.println("My Thread running");
}
}
ánd for the case of Runnable
class MyRunnable implements Runnable{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
}
}
and
Thread mythread = new MyThread();
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable());
myrunnable.start();

To start threads, you need to create two Threads from the Runnables and start them:
Thread t1 = new Thread(r);
Thread t2 = new Thread(a);
t1.start();
t2.start();

Define classes r1 and r2 as :
public class Thread1 extends Thread {
#Override
public void run() {
System.out.println("r1");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
public class Thread2 extends Thread {
#Override
public void run() {
System.out.println("r2");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
public class ThreadTester {
public static void main(String[] args) {
Thread1 r = new Thread1();
Thread2 a = new Thread2();
r.start();
a.start();
}
}
Using Runnable :
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
check java documentation for more info

Related

Why doesn't the volatile keyword work as expected in java code?

I'm learning concurrency knowledge in Java. About volatile keyword, it should make variable visible in different threads. But in my demo code, it doesn't seem to work as expected. The method run() in the class which implements Runnable will never stop.
public class VisibilityDemo {
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
Thread thread = new Thread(new TimeConsumingTask());
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel();
}
}
class TimeConsumingTask implements Runnable {
private volatile boolean toCancel = false;
#Override
public void run() {
while (! toCancel) {
System.out.println("executing...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (toCancel) {
System.out.println("Task was canceled.");
} else {
System.out.println("Task done.");
}
}
public void cancel() {
toCancel = true;
System.out.println(this + " canceled.");
}
}
In your main method you have two instances of your task:
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask(); //<-- one
Thread thread = new Thread(new TimeConsumingTask()); //<-- two
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel(); //<-- cancel() on first
}
}
You're passing one to the Thread constructor and then call cancel on the other one. You need to call cancel on the instance passed to Thread, like so:
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
Thread thread = new Thread(timeConsumingTask); //<-- difference here
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel();
}
}

How can i use callback method on my java code?

public class DowloadEngine implements Runnable {
public DowloadEngine(CallBack c) {
callback = c;
}
public interface CallBack {
public void processDone(String message);
}
private final CallBack callback;
#Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {}
callback.processDone("'CallBack' func is called");
}
}
And there is my main class in here
public class GUI implements DowloadEngine.CallBack{
public static void main(String[] args){
Thread thread = new Thread(new DowloadEngine(this));// Error :Make main not static!!
thread.start();
//wait a little to see the result
Scanner scan = new Scanner(System.in);
scan.nextLine();
//wait a little to see the result
}
#Override
public void processDone(String message) {
//code ...
//code ...
//code ...
System.out.println(message);
}
}
I want to do all works on main class via callback method but I did not understand these methodology. How does it works?
How can i use these with together?
Change:
Thread thread = new Thread(new DowloadEngine(this)); to
Thread thread = new Thread(new DowloadEngine(new GUI()));

Printing "Hello" and "world" multiple times using two threads in java

Assume that one thread prints "Hello" and another prints "World". I have done it successfully for one time, as follows:
package threading;
public class InterThread {
public static void main(String[] args) {
MyThread mt=new MyThread();
mt.start();
synchronized(mt){
System.out.println("Hello");
try {
mt.wait();
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread extends Thread{
public void run(){
synchronized(this){
System.out.println("World!");
notify();
}
}
}
How do I do it for multiple time printing, say for 5 times? I tried putting for loop around the synchronized block, but of no use.
Here being two interdependent threads, we need two synchronizing objects. they could be one of many things. one integer, another object; one Boolean another object; both object; both semaphores and so on. the synchronization technique could be either Monitor or Semaphore any way you like, but they have to be two.
I have modified your code to use semaphore instead of Monitor. The Semaphore works more transparently. You can see the acquire and release happening. Monitors are even higher constructs. Hence Synchronized works under the hood.
If you are comfortable with the following code, then you can convert it to use Monitors instead.
import java.util.concurrent.Semaphore;
public class MainClass {
static Semaphore hello = new Semaphore(1);
static Semaphore world = new Semaphore(0);
public static void main(String[] args) throws InterruptedException {
MyThread mt=new MyThread();
mt.hello = hello;
mt.world = world;
mt.start();
for (int i=0; i<5; i++) {
hello.acquire(); //wait for it
System.out.println("Hello");
world.release(); //go say world
}
}
}
class MyThread extends Thread{
Semaphore hello, world;
public void run(){
try {
for(int i = 0; i<5; i++) {
world.acquire(); // wait-for it
System.out.println(" World!");
hello.release(); // go say hello
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadSeq {
Object hello = new Object();
Object world = new Object();
public static void main(String[] args) throws InterruptedException {
for(int i=0; i<6;i++){
Runnable helloTask = new Runnable(){
#Override
public void run(){
new ThreadSeq().printHello();
}
};
Runnable worldTask = new Runnable(){
#Override
public void run(){
new ThreadSeq().printWorld();
}
};
Thread t1 = new Thread(helloTask);
Thread t2 = new Thread(worldTask);
t1.start();
t1.join();
t2.start();
t2.join();
}
}
public void printHello(){
synchronized (hello) {
System.out.println("Hello");
}
}
public void printWorld(){
synchronized (world) {
System.out.println("World");
}
}
}
The goal here is to synchronize threads so that when one is done it notify the other. If I have to make it, it would be 2 threads executing the same code with different data. Each thread has its own data ("Hello" and true to T1, "World" and false to t2), and share a variable turn plus a separate lock object.
while(/* I need to play*/){
synchronized(lock){
if(turn == myturn){
System.out.println(mymessage);
turn = !turn; //switch turns
lock.signal();
}
else{
lock.wait();
}
}
}
Before you start trying to get it to work five times you need to make sure it works once!
Your code is not guaranteed to always print Hello World! - the main thread could be interrupted before taking the lock of mt (note that locking on thread objects is generally not a good idea).
MyThread mt=new MyThread();
mt.start();
\\ interrupted here
synchronized(mt){
...
One approach, that will generalise to doing this many times, is to use an atomic boolean
import java.util.concurrent.atomic.AtomicBoolean;
public class InterThread {
public static void main(String[] args) {
int sayThisManyTimes = 5;
AtomicBoolean saidHello = new AtomicBoolean(false);
MyThread mt=new MyThread(sayThisManyTimes,saidHello);
mt.start();
for(int i=0;i<sayThisManyTimes;i++){
while(saidHello.get()){} // spin doing nothing!
System.out.println("Hello ");
saidHello.set(true);
}
}
}
class MyThread extends Thread{
private final int sayThisManyTimes;
private final AtomicBoolean saidHello;
public MyThread(int say, AtomicBoolean said){
super("MyThread");
sayThisManyTimes = say;
saidHello = said;
}
public void run(){
for(int i=0;i<sayThisManyTimes;i++){
while(!saidHello.get()){} // spin doing nothing!
System.out.println("World!");
saidHello.set(false);
}
}
}
This is in C:
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t hello_lock, world_lock;
void printhello()
{
while(1) {
pthread_mutex_lock(&hello_lock);
printf("Hello ");
pthread_mutex_unlock(&world_lock);
}
}
void printworld()
{
while(1) {
pthread_mutex_lock(&world_lock);
printf("World ");
pthread_mutex_unlock(&hello_lock);
}
}
int main()
{
pthread_t helloThread, worldThread;
pthread_create(&helloThread,NULL,(void *)printhello,NULL);
pthread_create(&helloThread,NULL,(void *)printhello,NULL);
pthread_join(helloThread);
pthread_join(worldThread);
return 0;
}
There are two thread and both has its own data ("Hello" and true to ht, "World" and false to wt), and share a variable objturn.
public class HelloWorldBy2Thread {
public static void main(String[] args) {
PrintHelloWorld hw = new PrintHelloWorld();
HelloThread ht = new HelloThread(hw);
WorldThread wt = new WorldThread(hw);
ht.start();
wt.start();
}
}
public class HelloThread extends Thread {
private PrintHelloWorld phw;
private String hello;
public HelloThread(PrintHelloWorld hw) {
phw = hw;
hello = "Hello";
}
#Override
public void run(){
for(int i=0;i<10;i++)
phw.print(hello,true);
}
}
public class WorldThread extends Thread {
private PrintHelloWorld phw;
private String world;
public WorldThread(PrintHelloWorld hw) {
phw = hw;
world = "World";
}
#Override
public void run(){
for(int i=0;i<10;i++)
phw.print(world,false);
}
}
public class PrintHelloWorld {
private boolean objturn=true;
public synchronized void print(String str, boolean thturn){
while(objturn != thturn){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(str+" ");
objturn = ! thturn;
notify();
}
}
In simple way we can do this using wait() and notify() without creating any extra object.
public class MainHelloWorldThread {
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
Thread t1 = new Thread(() -> {
try {
helloWorld.printHello();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
helloWorld.printWorld();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// printHello() will be called first
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
class HelloWorld {
public void printHello() throws InterruptedException {
synchronized (this) {
// Infinite loop
while (true) {
// Sleep for 500ms
Thread.sleep(500);
System.out.print("Hello ");
wait();
// This thread will wait to call notify() from printWorld()
notify();
// This notify() will release lock on printWorld() thread
}
}
}
public void printWorld() throws InterruptedException {
synchronized (this) {
// Infinite loop
while (true) {
// Sleep for 100ms
Thread.sleep(100);
System.out.println("World");
notify();
// This notify() will release lock on printHello() thread
wait();
// This thread will wait to call notify() from printHello()
}
}
}
}

How do I implement thread wait notify in this case?

I have 2 classes. One method of the class calls the other class' method, but it has to wait until the method finishes to proceed to the execution of the rest of the code.
This is a rough code of what I'm trying to make. And I know this doesn't work.
public class Example
{
Thread thread;
public Example(Thread thread)
{
this.thread = thread;
}
public void doSomethingElse()
{
System.out.println("Do something else");
thread.notify();
}
}
public class Example2
{
Thread thread;
Example example;
public Example2()
{
example = new Example(thread);
thread = new Thread()
{
public void run()
{
example.doSomethingElse();
try {
this.wait();
} catch (InterruptedException ex) {
}
System.out.println("Do something");
}
};
}
public void doSomething()
{
thread.run();
}
}
Now do you know how to make this right?
Not sure if your constrained to using this particular approach (wait/notify) however a better approach is taking advantage of the Java Concurrency API
public class ExampleCountDownLatch
{
public void doSomething () throws InterruptedException
{
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread()
{
public void run ()
{
System.out.println("do something");
latch.countDown();
}
};
System.out.println("waiting for execution of method in your example class");
thread.start();
// wait for reasonable time otherwise kill off the process cause it took
// too long.
latch.await(3000, TimeUnit.MILLISECONDS);
// now I can do something from your example 2
System.out.println("now i can execute from example 2 do something else");
}
}
Anyway just another approach if you had an option.
UPDATE:
Here is a blog about this very topic.
Couple of points :
you should acquire lock before calling wait or notify method. The
lock must be on same object. In code you are calling wait on example2
object but calling notify on different object.
thread.run() means calling run method of thread object, its not
creating new thread its same as example.doSomething(). When you
create thread start that thread by calling start method.
Here is my implementation
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
synchronized(this){
System.out.println("Do something else");
try{
Thread.sleep(1000);
this.notify();
}catch (InterruptedException ignore) {}
}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
doSomething();
}
public void doSomething(){
synchronized(example){
System.out.println("waiting for example 1 to complete");
try{
example.wait();
}catch (InterruptedException ignore) {}
}
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
Thread t2 = new Thread(example);
t2.start();
}
}
In code Thread.sleep(1000); statement is not needed.
Here is one more implementation using join method
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
System.out.println("Do something else");
try{
Thread.sleep(1000);
}catch (InterruptedException ignore) {}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
System.out.println("waiting for example 1 to complete");
Thread t = new Thread(example);
try{
t.start();
t.join();
}catch(InterruptedException ie){
}
doSomething();
}
public void doSomething(){
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
}
}

Thread Dependency Java

I have a main class which spawns a thread, let's call them MainClass and MyThread.
public class MainClass extends javax.swing.JFrame {
int sharedVariable;
MyThread threadInstance;
public MainClass (){
sharedVariable = 2;
threadInstance = new MyThread(this);
threadInstance.run();
}
public int getSharedVariable(){ return sharedVariable; }
public static void main(String[] args){
//begin main class
}
}
public class MyThread implements Runnable {
MainClass class;
public MyThread(MainClass main_class){
this.main_class= main_class;
}
#Override
public run(){
while(this.main_class is still active){
//grab status of sharedVariable and wait for x amount of time.
}
}
}
The problem is I do not know how to implement the while condition which checks if the MainClass instance is still alive and if it is, it has to use the this.main_class.getSharedVariable() to get the value of sharedVariable, then wait for x amount of time. MainClass has the main method .
I would recommend holding onto the Thread instance and then calling threadInstance.interrupt() right before the main(...) method exits.
Something like:
public static void main(String[] args){
MainClass mainClass = new MainClass();
try {
...
// do main stuff here
...
} finally {
mainClass.threadInstance.interrupt();
}
}
Then in your thread you'd do:
while(!Thread.currentThread().isInterrupted()){
...
}
You'd also want to handle InterruptedException correctly:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// always a good pattern to re-interrupt the thread here
Thread.currentThread().interrupt();
// if we are interrupted quit
return;
}
Btw, it is very bad form to leak the instance of an object during construction to another thread:
new MyThread(this);
See here: Why shouldn't I use Thread.start() in the constructor of my class?
Also, you aren't starting a thread when you call threadInstance.run();. You are just running it in the current thread. You should use threadInstance.start() but not inside of the constructor like that.
You can use CountDownLatch which is very convenient for such tasks as waiting other threads to finish some activity (you can change Thread.sleep(...) argument in main to, say, 12000L and see what happens):
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
class OtherThread extends Thread {
private final CountDownLatch sharedLatch;
OtherThread(CountDownLatch sharedLatch) {
this.sharedLatch = sharedLatch;
}
#Override
public void run() {
boolean wokenByMain = false;
try {
wokenByMain = sharedLatch.await(10000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
return; // or not return, whatever makes more sense in your case
}
System.out.println("heh: " + wokenByMain);
}
}
class SOSample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
OtherThread otherThread = new OtherThread(latch);
otherThread.start();
System.out.println("Scheduled other thread to be started");
Thread.sleep(1000L);
System.out.println("going to release other thread");
latch.countDown();
}
}
public class MainClass extends JFrame implements Runnable {
public static void main(String [] args) {
final Thread t=new Thread(new MainClass() {
public void run(){
//something
});
Thread t2=new Thread(new MyThread() {
public void run() {
while(t.isAlive) {
//something
}
}
});
}
}

Categories