I have the following code to test multithreading. Inside the run() method, I have a loop. I instantiate my Runnable class and pass the object thus created to two different threads. My question is- How does the JVM deal with loop indexes ? Since a single Runnable object is passed to two different threads, won't it create confusion with loop indexes ?
public class ThreadTest1 implements Runnable{
public static void main(String[] args) {
ThreadTest1 tt = new ThreadTest1();
Thread t1 = new Thread(tt);
Thread t2 = new Thread(tt);
t1.start();
t2.start();
}
private synchronized void b() {
try {
for(int ii = 0; ii < 2; ii++) {
Thread.sleep(1000);
System.out.println("inside method 'b': " + this.toString() + " " + Thread.currentThread());
}
}
catch (InterruptedException e) {e.printStackTrace();}
}
#Override
public void run() {
this.b();
}
}
Related
I many examples in Internet there are almost all the same:
public class Test extends Thread {
public synchronized void run() {
for (int i = 0; i <= 10; i++) {
System.out.println("i::"+i);
}
}
public static void main(String[] args) {
Test obj = new Test();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
Thread t3 = new Thread(obj);
t1.start();
t2.start();
t3.start();
}
}
So why would I call same task (in run() method) three times with different threads? E.g. if I want to upload a file, then why would I call it three times?
I assume if I need multithreading then:
thread t1 would do task1, e.g.:
- update database info
thread t2 would do task2, e.g.:
- upload file to server
thread t3 would do task3, e.g.:
- bring a message to an user
Is there an example that would to work like that described above.
You can create multiple threads the code given below where you only start thread and you don't need to call multiple times a same method. As you can see, once it started, all three child threads share the CPU. Notice the call to sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and ensures that it will finish last.
// Create multiple threads.
class NewThread implements Runnable
{
String name;
} // name of thread Thread t;
NewThread(String threadname)
{
name = threadname;
}
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Reference from The Complete Reference By Herbert Schildt
I am learning about the use of semaphores and multi threading in general but am kind of stuck. I have two threads printing G and H respectively and my objective is to alternate the outputs of each thread so that the output string is like this;
G
H
G
H
G
H
Each of the two classes has a layout similar to the one below
public class ClassA extends Thread implements Runnable{
Semaphore semaphore = null;
public ClassA(Semaphore semaphore){
this.semaphore = semaphore;
}
public void run() {
while(true)
{
try{
semaphore.acquire();
for(int i=0; i<1000; i++){
System.out.println("F");
}
Thread.currentThread();
Thread.sleep(100);
}catch(Exception e)
{
System.out.println(e.toString());
}
semaphore.release();
}
}
}
below is my main class
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(1);
ClassA clasA = new ClassA(semaphore);
Thread t1 = new Thread(clasA);
ClassB clasB = new ClassB(semaphore);
Thread t2 = new Thread(clasB);
t1.start();
t2.join();
t2.start();
The output I am getting is way too different from my expected result. can anyone help me please? did I misuse the semaphore? any help?
Semaphores can't help you solve such a task.
As far as I know, JVM doesn't promise any order in thread execution. It means that if you run several threads, one thread can execute several times in a row and have more processor time than any other. So, if you want your threads to execute in a particular order you can, for the simplest example, make a static boolean variable which will play a role of a switcher for your threads. Using wait() and notify() methods will be a better way, and Interface Condition will be the best way I suppose.
import java.io.IOException;
public class Solution {
public static boolean order;
public static void main(String[] args) throws IOException, InterruptedException {
Thread t1 = new ThreadPrint("G", true);
Thread t2 = new ThreadPrint("O", false);
t1.start();
t2.start();
t2.join();
System.out.println("Finish");
}
}
class ThreadPrint extends Thread {
private String line;
private boolean order;
public ThreadPrint(String line, boolean order) {
this.line = line;
this.order = order;
}
#Override
public void run() {
int z = 0;
while (true) {
try {
for (int i = 0; i < 10; i++) {
if (order == Solution.order) {
System.out.print(line + " ");
Solution.order = !order;
}
}
sleep(100);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
}
BTW there can be another problem cause System.out is usually an Operation System buffer and your OS can output your messages in an order on its own.
P.S. You shouldn't inherit Thread and implement Runnable at the same time
public class ClassA extends Thread implements Runnable{
because Thread class already implements Runnable. You can choose only one way which will be better for your purposes.
You should start a thread then join to it not vice versa.
t1.start();
t2.join();
t2.start();
As others have pointed out, locks themselves do not enforce any order and on top of that, you cannot be certain when a thread starts (calling Thread.start() will start the thread at some point in the future, but this might take a while).
You can, however, use locks (like a Semaphore) to enforce an order. In this case, you can use two Semaphores to switch threads on and off (alternate). The two threads (or Runnables) do need to be aware of each other in advance - a more dynamic approach where threads can "join in" on the party would be more complex.
Below a runnable example class with repeatable results (always a good thing to have when testing multi-threading). I will leave it up to you to figure out why and how it works.
import java.util.concurrent.*;
public class AlternateSem implements Runnable {
static final CountDownLatch DONE_LATCH = new CountDownLatch(2);
static final int TIMEOUT_MS = 1000;
static final int MAX_LOOPS = 10;
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
AlternateSem as1 = new AlternateSem(false);
AlternateSem as2 = new AlternateSem(true);
as1.setAlternate(as2);
as2.setAlternate(as1);
executor.execute(as1);
executor.execute(as2);
if (DONE_LATCH.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
System.out.println();
System.out.println("Done");
} else {
System.out.println("Timeout");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdownNow();
}
}
final Semaphore sem = new Semaphore(0);
final boolean odd;
AlternateSem other;
public AlternateSem(boolean odd) {
this.odd = odd;
}
void setAlternate(AlternateSem other) { this.other = other; }
void release() { sem.release(); }
void acquire() throws Exception { sem.acquire(); }
#Override
public void run() {
if (odd) {
other.release();
}
int i = 0;
try {
while (i < MAX_LOOPS) {
i++;
other.acquire();
System.out.print(odd ? "G " : "H ");
release();
}
} catch (Exception e) {
e.printStackTrace();
}
DONE_LATCH.countDown();
}
}
I have implemented two threads, one to print integers and other one to print English alphabets. The threads are supposed to work in tandem.
I use a synchronized block and only one thread will hold the lock at a time. But somehow, the AtomicInteger is not working as expected. The changes to count variable made by one thread is not visible to other different thread. How's this possible. Am i missing something?
My Implementation
package com.concurrency;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadWaitEg
{
// Single monitor object for both threads
private final Object monitor = new Object();
// Thread-safe counter for both threads
private final AtomicInteger count = new AtomicInteger(0);
private class PrintNumber implements Runnable
{
#Override
public void run()
{
for (int i = 0; i < 26; i++)
{
synchronized (monitor)
{
System.out.println("From PrintNumber "+count.get());
try
{
while ((count.get()) % 2 != 0)
{
monitor.wait();
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(i);
count.getAndIncrement();
monitor.notifyAll();
}
}
}
}
private class PrintChar implements Runnable
{
#Override
public void run()
{
for (int charr = 'A'; charr <= 'Z'; charr++)
{
synchronized (monitor)
{
System.out.println("From PrintChar "+count.get());
try
{
while ((count.get()) % 2 == 0)
{
monitor.wait();
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println((char) charr);
count.getAndIncrement();
monitor.notifyAll();
}
}
}
}
public static void main(String[] args)
{
System.out.println("from main thread");
Runnable runInt = new ThreadWaitEg().new PrintNumber();
new Thread(runInt).start();
Runnable runChar = new ThreadWaitEg().new PrintChar();
new Thread(runChar).start();
System.out.println(" main thread completes ");
}
}
Output
from main thread
From PrintNumber 0
0
From PrintNumber 1
main thread completes
From PrintChar 0
Your main problem is that you create two instances of the main ThreadWaitEg class - each with its own copy of the "monitor" and "count" objects, thus the objects are not shared between the two threads. The quickest fix is to create just a single instance, i.e. replace you main() method with:
public static void main(String[] args) {
System.out.println("from main thread");
ThreadWaitEg threadWaitEg = new ThreadWaitEg();
Runnable runInt = threadWaitEg.new PrintNumber();
new Thread(runInt).start();
Runnable runChar = threadWaitEg.new PrintChar();
new Thread(runChar).start();
System.out.println(" main thread completes ");
}
here is my class
public class ThreadTest {
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.m1();
synchronized (threadTest) {
threadTest.m2();
}
System.out.println("End of main thread");
}
public void m1() {
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
System.out.println("end of mythread");
}
});
myThread.start();
}
public void m2() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
Although i put my code inside synchronized block it doesn't seem to work properly and both of for loops are run parallelly.How can i run those loops as threadsafe in multi-threaded environment with a synchronized block.Where is the mistake i made my code given?
thanks!
A synchronized block prevents other threads to enter the same or another synchonized block on the same object. You have a single synchronized block here, and only one thread enters it. So all the other threads can execute whatever they want.
How can I start two threads where thread1 executes first, thread2 starts when thread1 ends while the main method thread can continue its work without locking on the other two?
I have tried join() however it needs to be called from the thread which has to wait for the other, there's no way to do something like thread2.join(thread1);
If I call for a join inside main() I therefore effectively stop execution of the main thread and not only of thread2.
I therefore tried with ExecutorService but again same problem.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Test
{
public static void main(String args[]) throws InterruptedException
{
System.out.println(Thread.currentThread().getName() + " is Started");
class TestThread extends Thread
{
String name;
public TestThread(String name)
{
this.name = name;
}
#Override
public void run()
{
try
{
System.out.println(this + " is Started");
Thread.sleep(2000);
System.out.println(this + " is Completed");
}
catch (InterruptedException ex) { ex.printStackTrace(); }
}
#Override
public String toString() { return "Thread " + name; }
}
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new TestThread("1"));
boolean finished = executor.awaitTermination(1, TimeUnit.HOURS);
if(finished)
{
//I should execute thread 2 only after thread 1 has finished
executor.execute(new TestThread("2"));
}
//I should arrive here while process 1 and 2 go on with their execution
System.out.println("Hello");
}
}
#EDIT: Why I need this:
I need this because Thread1 copies elements from a database table into another database, thread2 has to copy a linking table which references the table copied from thread1.
Consequently thread2 has to start populating its linking table only when thread1 has finished otherwise an integrity error is given by the database.
Now imagine I have several threads with different priorities due to complex linking tables and you have an idea.
The second Thread can be custom like this (takes as argument the previous thread):
public static void main(String[] a) {
Thread first = new Thread(new Runnable() {
#Override
public void run() {
}
});
Thread second = new MyThread(first);
first.start();
second.start();
//continue executing
}
public static class MyThread extends Thread {
private Thread predecessor;
public MyThread(Thread predecessor) {
this.predecessor = predecessor;
}
public void run() {
if (predecessor != null && predecessor.isAlive()) {
try {
predecessor.join();
} catch (InterruptedException e) {}
}
//do your stuff
}
}
You can use a CountDownLatch:
create it in the main thread, pass it on to both threads and call countdown on it in thread one when it exits and await it being counted down at the start of thread 2.
I am pretty sure you got something wrong because this must work and it does work:
new Thread() {
#Override
public void run() {
TestThread t1= new TestThread("1");
TestThread t2= new TestThread("2");
try {
t1.start();
t1.join();
t2.start();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
The ouput is:
main is Started
Hello
Thread 1 is Started
Thread 1 is Completed
Thread 2 is Started
Thread 2 is Completed
Another option would be to extend the TestThread for the "Thread 1" to execute the work of "Thread 2" after it has been done with its own work. Something similar to this:
final TestThread t2= new TestThread("2");
TestThread t1= new TestThread("1") {
#Override
public void run() {
super.run(); //finish t1 work
t2.start(); // start t2 work
}
};
t1.start();
Why not just have thread1 be the one to start thread2?
// in main
new Thread(new Runnable() {
#Override public void run() {
// do thread1 work
new Thread(new Runnable() {
#Override public void run() { /* do thread2 work */ }
}).start();
}
}).start();
However, it's not at all clear why you would want to do this as opposed to just having thread1 do 100% of the background work.
You can use SingleThreadExecutor to run one task after another Java doc
So it will put your task one after another and they will execute in sequence without blocking main thread
Try this, This will work as expected. Two threads printing odd and even one after another and main exiting as soon as possible.
public class YoThreD {
static boolean isThread1 = false;
public static synchronized boolean isThread1() {
return isThread1 = !isThread1;
}
public static void main(String args[]) {
Runnable runnableObject = new Runnable() {
#Override
public void run() {
synchronized (this) {
for (int i = 1; i <= 100; i++) {
try {
if (Thread.currentThread().getName().equals("thread1")) {
if (isThread1()){
System.out.println(Thread.currentThread().getName() + " : " + i);
}else{
this.notify();
this.wait();
}
} else {
if (!isThread1()){
System.out.println(Thread.currentThread().getName() + " : " + i);
this.notify();
this.wait();
}
else{
}
}
} catch (Exception e) {
}
}
}
}
};
Thread thread1 = new Thread(runnableObject);
thread1.setName("thread1");
thread1.start();
Thread thread2 = new Thread(runnableObject);
thread2.setName("thread2");
thread2.start();
System.out.println(Thread.currentThread().getName() + "Main thread finished");
}
}
Silly question, but if thread 2 is supposed to execute when thread 1 is done... why not just start it from thread 1?
Or maybe just have thread 1 trigger an event and the main thread can just launch the new one in response to that.
I found this example, should work for you.
You can run two thread one after other by using several ways:
by using join() method. ex:
Thread t1=new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println("A " + i);
}
}
});
Thread t2=new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println("B " + i);
}
}
});
by using wait() and notify() methods: ex.
`
{
public class NotiffyAllExample {
int flag = 1;
public static void main(String[] args) {
NotiffyAllExample notiffyAllExample = new NotiffyAllExample();
A1 a = new A1(notiffyAllExample);
B1 b = new B1(notiffyAllExample);
C1 c = new C1(notiffyAllExample);
a.start();
b.start();
}
}
class A1 extends Thread {
NotiffyAllExample notiffyAllExample;
public A1(net.citigroup.mexico.pg.test.test.NotiffyAllExample notiffyAllExample) {
this.notiffyAllExample = notiffyAllExample;
}
#Override
public void run() {
try {
synchronized (notiffyAllExample) {
for (int i = 0; i < 4; i++) {
while (notiffyAllExample.flag != 1) {
notiffyAllExample.wait();
}
System.out.print("A ");
}
notiffyAllExample.flag = 2;
notiffyAllExample.notifyAll();
}
} catch (Exception e) {
System.out.println("Exception 1 :" + e.getMessage());
}
}
}
class B1 extends Thread {
NotiffyAllExample notiffyAllExample;
public B1(NotiffyAllExample notiffyAllExample) {
this.notiffyAllExample = notiffyAllExample;
}
#Override
public void run() {
try {
synchronized (notiffyAllExample) {
for (int i = 0; i < 4; i++) {
while (notiffyAllExample.flag != 2) {
notiffyAllExample.wait();
}
System.out.print("B ");
}
notiffyAllExample.flag = 1;
notiffyAllExample.notifyAll();
}
} catch (Exception e) {
System.out.println("Exception 2 :" + e.getMessage());
}
}
}
}
`