I was just trying to run multiple threads with CyclicBarrier limit:3 but threads are run more or less than limit
.
In CyclicBarrierDemo (in main thread) I create CyclicBarrier object with limit 3 and BarAction thread, and after that I excute multiple threads object of Waiting thread.
And as I expect it execute BarAction thread after any 3 thread but it not.
public class CyclicBarrierDemo {
public static void main(String args[]){
CyclicBarrier cb = new CyclicBarrier(3, () -> System.out.println("Reached Barrier!"));
System.out.println("Starting...");
new WaitingThread(cb, "A");
new WaitingThread(cb, "B");
new WaitingThread(cb, "C");
}
}
class WaitingThread implements Runnable{
CyclicBarrier cb;
String name;
public WaitingThread(CyclicBarrier cb, String name) {
this.cb = cb;
this.name = name;
new Thread(this).start();
}
public void run(){
System.out.println(name);
try{
cb.await();
}catch(InterruptedException e){
System.out.println(name+" was interrupted!");
}catch(BrokenBarrierException e){
System.out.println(name+"broken barrier occur!");
}
}
}
Sorry I am new in java and also search on google and stackoverflow but did'n get satisfied answer.
Apprecite to helping.
Related
I have a threadpool of a fixed size 12. Now I have two classes that implement Runnable and 20 objects of each class. I can submit all the tasks and the threadpool will do its job as regular.
What I would like to do is to make a delimiter. So, in case that I submit this 40 tasks, the thread pool will not process more than 6 of each class concurrently. So the thread pool will behabe like 2 smaller thread pool of size 6. Is it possible by the API of java or guava?
Without questioning the "why" - it can be achieved using semaphores, each of them created with the count of 6, each of them delimiting the number of tasks of each type to exactly 6 at the same time.
Here is a basic working sample:
public class TaskDelimitingTest {
private enum Tasks {TASK1, TASK2};
private static ConcurrentHashMap<Tasks, AtomicInteger> taskObserver = new ConcurrentHashMap<>();
public static class Task implements Runnable {
private static final Random random = new Random(System.currentTimeMillis());
private final Semaphore sem = new Semaphore(6, true);
private final Tasks task;
public Task(Tasks task) {
this.task = task;
}
#Override
public void run() {
try {
taskObserver.get(task).incrementAndGet();
Thread.sleep(random.nextInt(1000));
taskObserver.get(task).decrementAndGet();
sem.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void postToExecution(ExecutorService executor) {
try {
sem.acquire();
executor.execute(this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class Task1 extends Task {
public Task1() {
super(Tasks.TASK1);
}
}
public static class Task2 extends Task {
public Task2() {
super(Tasks.TASK2);
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(12);
Thread t1 = new Thread(() -> {
taskObserver.put(Tasks.TASK1, new AtomicInteger());
IntStream.rangeClosed(1, 100).forEach(i -> {
new Task1().postToExecution(executor);
System.out.println(taskObserver);
});
});
Thread t2 = new Thread(() -> {
taskObserver.put(Tasks.TASK2, new AtomicInteger());
IntStream.rangeClosed(1, 100).forEach(i -> {
new Task2().postToExecution(executor);
System.out.println(taskObserver);
});
});
t1.start();
t2.start();
}
}
In this example I create 100 tasks of each of the two types in two separate threads, so that they can compete with each other, I also put a Thread.sleep in the run method so that they simulate different execution time.
The output of this programm is - In the "warmup" phase
{TASK2=1, TASK1=1}
...
{TASK2=2, TASK1=3}
...
{TASK2=4, TASK1=3}
...
{TASK2=4, TASK1=4}
...
{TASK2=4, TASK1=5}
...
at some time the pool gets saturated and then it goes only like that:
{TASK2=6, TASK1=6}
...
So only at maximum 6 threads of each type are being executed simultanously.
I was just experimenting some code around Thread class and I get stuck at something, Well firstly have a look at my code
class ThreadExample implements Runnable
{
String threadName;
Thread thread;
public ThreadExample()
{
thread=new Thread();
thread.start();
}
public void run()
{
System.out.println("Thread "+getThreadName()+" is being executed");
}
void setThreadName(String string)
{
threadName=string;
thread.setName(string);
}
String getThreadName()
{
return thread.getName();
}
public static void main(String string[]) throws InterruptedException
{
ThreadExample threadExample= new ThreadExample();
threadExample.setThreadName("Thread !");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 2");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 3");
Thread.sleep(500);
}
}
Well I think this code is very simple and Everyone should have got my intentions although When I am running this program It just get complete without even calling run() method even I make main Thread to wait for sometime until the child Thread which is ThreadExample completes. I am new to this so sorry if I have forgotten some thing. Thanks in advance.
You created a Runnable type and never passed it into a thread context. You'll want to add it to the Thread. I would do something like:
String threadName;
Thread thread;
public ThreadExample() {
thread=new Thread(this);
}
public void startThread() {
thread.start();
}
The Thread class accepts a Runnable as an argument.
You never call run() method. You rather call start, which you are already doing in ThreadExample() constructor, but it has some mistakes I will explain:
In java you have 2 options to deal with Threads. First is to inherit from Thread class, so you can call start() method from it and the code inside run() will be executed. The second option is to create a Runnable, which seems the option you are choosing, but to run this you have to create a Thread like this:
ThreadExample runnable = new ThreadExample();
Thread myThread = new Thread(threadExample);
And then you can call myThread.start(); when you are ready to start your thread.
As John Vint has pointed out, the Thread class needs a Runnable target. I edited your program a little :
public class NewThreadExample implements Runnable{
String threadName;
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
public static void main(String[] args) throws InterruptedException {
NewThreadExample threadTarget = new NewThreadExample();
threadTarget.setThreadName("Dushyant");
Thread thread = new Thread(threadTarget);
System.out.println("Thread created and going to start");
thread.start();
System.out.println("Thread sleeping");
Thread.sleep(2000);
System.out.println("Program done");
}
#Override
public void run() {
System.out.println(this.getThreadName() + " is running...");
}
}
gives
Thread created and going to start
Thread sleeping
Dushyant is running...
Program done
To run this implementation class, create a Thread object, pass Runnable implementation class object to its constructor. Call start() method on thread class to start executing run() method.
You missed following two lines:
Thread thread1 = new Thread(threadExample);
thread1.start();
class ThreadExample implements Runnable
{
String threadName;
Thread thread;
public ThreadExample()
{
}
public void run()
{
System.out.println("Thread "+getThreadName()+" is being executed");
}
void setThreadName(String string)
{
threadName=string;
thread.setName(string);
}
String getThreadName()
{
return thread.getName();
}
public static void main(String string[]) throws InterruptedException
{
ThreadExample threadExample= new ThreadExample();
threadExample.setThreadName("Thread !");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 2");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 3");
Thread.sleep(500);
Thread thread1 = new Thread(threadExample);
thread1.start();
}
}
i'm wondering what the code would look like in order to have a program which creates a loop on start. This loop then creates several, thread objects all on their own threads so their all running at the same time, and they all run the same code. Is there a way to do this? as in for example we make 2 threads, they never stop looping and one is always prinintg "thread 1" and 1 is always printing "thread 2" at the same time. This is what i'm wondering. Thanks in advance!
class MyTask implements Runnable {
public static id = 0;
public MyTask(){
id++;
}
public void run(){
while(true){
System.out.print("Thread " + id);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Generator{
Public static void main(String[] args){
Runnable[] myTasks = new Runnable[2];
myTasks[0] = new MyTask();
myTasks[1] = new MyTask();
for(Runnable r: myTasks){
Thread t = new Thread(r);
t.start();
}
}
}
I didn't compile it. but this is how you are going to do.
When you run class Generator, two Threads will start, and they will print Thread 1. and thread 2 once every one second forever.
I am writing a code in java to print the output as follows
[spirit]
[of]
[wipro]
but i am facing a problem in setting the priorities of the threads and seeing each threads priorty and not getting output as expected.
class shobj
{
public synchronized void sharedMethod(String arg)
{
System.out.print("[");
System.out.print(arg);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("INTERRUPTED");
}
System.out.println("]");
}
}
class thread1 implements Runnable
{
String arg;
shobj obj1;
Thread t;
public thread1(shobj obj1,String arg)
{
this.obj1=obj1;
this.arg=arg;
t=new Thread(this);
t.start();
// System.out.println(t.currentThread());
}
public void run()
{
obj1.sharedMethod(arg);
}
}
class synchro
{
public static void main(String args[])
{
shobj ob = new shobj();
thread1 x1 = new thread1(ob,"spirit");
thread1 x2 = new thread1(ob,"of");
thread1 x3 = new thread1(ob,"wipro");
x3.t.setPriority(Thread.NORM_PRIORITY+3);
x2.t.setPriority(Thread.NORM_PRIORITY+2);
x1.t.setPriority(Thread.NORM_PRIORITY+1);
try
{
x1.t.join(); //System.out.println(x1.t.currentThread());
x2.t.join();//System.out.println(x2.t.currentThread());
x3.t.join();//System.out.println(x3.t.currentThread());
}
catch(Exception e)
{
System.out.println("Interruted Exception");
}
}
}
I am getting output as follows:
[spirit]
[wipro]
[of]
See How are Java Thread priorities translated to an OS thread priority? how the thread priority is mapped to the native OS. There is no guarantee that different thread priorities in java lead to different priority on OS level.
Priority is just a hint to the OS. If you have plenty of free CPU, all thread which want to run, can run.
This means all the threads in your case could run in any order which is what having multiple threads is designed to.
How can I make a thread run only if the other thread is running too, meaning, if I return from run in one thread, then I want the other to stop running too,
my code looks something like this:
ClientMessageHandler clientMessagehandler = new ClientMessageHandler();
ServerMessageHandler serverMessagehandler = new ServerMessageHandler();
Thread thread1 = new Thread(serverMessagehandler);
Thread thread2 = new Thread(clientMessagehandler);
thread2.start();
thread1.start();
I want to cause thread1 to stop running when thread2 stops running.
edit: detecting when thread2 stops running in order stop thread1 from running, and not how to stop thread1 from running
thanks
This minimal example should demonstrate the basic idea:
import java.io.*;
import java.util.concurrent.LinkedBlockingQueue;
public class Test {
static LinkedBlockingQueue<String> msgBuf = new LinkedBlockingQueue<String>();
static volatile boolean keepRunning = true;
static Thread thread1, thread2;
public static void main(String[] args) throws IOException {
ClientMessageHandler clientMessagehandler = new ClientMessageHandler();
ServerMessageHandler serverMessagehandler = new ServerMessageHandler();
thread1 = new Thread(serverMessagehandler);
thread2 = new Thread(clientMessagehandler);
thread2.start();
thread1.start();
}
}
class ClientMessageHandler implements Runnable {
public void run() {
while (Test.keepRunning) {
try {
String msg = Test.msgBuf.take();
System.out.println("Eating " + msg);
} catch (InterruptedException ie) {
}
}
}
}
class ServerMessageHandler implements Runnable {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String in;
try {
while (!(in = br.readLine()).equals("quit")) {
System.out.println("Feeding " + in);
Test.msgBuf.offer(in);
}
} catch (IOException e) {
}
Test.keepRunning = false;
Test.thread2.interrupt();
}
}
Edit for question clarification
I see two immediate options:
Option 1. Have the ClientMessageHandler implementation terminate the ServerMessageHandler as it terminates. This means the client needs a reference to the server thread.
public class ClientMessageHandler implements Runnable {
Thread serverThread;
public ClientMessageHandler(Thread srvThread) {
this.serverThread = srvThread;
}
public void run() {
try {
while (true) { ... }
} finally {
serverThread.interrupt();
}
}
}
Option 2. Use thread2.join() or a CountDownLatch to wait for thread2 to terminate. When control returns from the join (or CountDownLatch#await()).
ClientMessageHandler clientMessagehandler = new ClientMessageHandler();
ServerMessageHandler serverMessagehandler = new ServerMessageHandler();
Thread thread1 = new Thread(serverMessagehandler);
Thread thread2 = new Thread(clientMessagehandler);
thread2.start();
thread1.start();
thread2.join(); //blocks until the client terminates
thread1.interrupt();
Make sure that inside thread1's run method, you have some logical place where you can check the interrupt status (Thread#isInterrupted()) and decide to terminate. Also, you must take care to handle InterruptedException properly and either terminate or reset the interrupt flag.
A Thread will only stop when the run() method returns. The Thread#interrupt() only signals that a request for interruption has made. You still have to write the code in run() method accordingly that it periodically checks Thread#isInterrupted() and handle accordingly. E.g. check for it on every unit of task the Thread is doing, or on every certain progress when sort of progresslistener is attached.