logo
down
shadow

Program hangs indefinitely after two threads print even off numbers alternatively


Program hangs indefinitely after two threads print even off numbers alternatively

Content Index :

Program hangs indefinitely after two threads print even off numbers alternatively
Tag : java , By : Lex Viatkine
Date : November 24 2020, 01:01 AM

Does that help Having printed out 100, the even thread then enters lock.wait();. There is nothing to take it out of that wait (the other thread has either already terminated, or will terminate imminently), so it sits there forever.

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Multi threaded java program to print even and odd numbers alternatively


Tag : java , By : hyperNURb
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Well, there are many alternatives. I would probably use a SynchronousQueue instead (I don't like low-level wait/notify and try to use higher-level concurrency primitives instead). Also printOdd and printEven could be merged into single method and no additional flags are necessary:
public class App {
    static class OddEven implements Runnable {
        private final SynchronousQueue<Integer> queue = new SynchronousQueue<>();

        public void start() throws InterruptedException {
            Thread oddThread = new Thread(this);
            Thread evenThread = new Thread(this);
            oddThread.start();
            queue.put(1);
            evenThread.start();
        }

        @Override
        public void run() {
            try {
                while (true) {
                    int i = queue.take();
                    System.out.println(i + " (" + Thread.currentThread() + ")");
                    if (i == 10)
                        break;
                    queue.put(++i);
                    if (i == 10)
                        break;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new OddEven().start();
    }
}

[Print alternatively using alternate Threads]


Tag : multithreading , By : Giles
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You will need the highest Id given to your threads. After this, you can simplify your code using the modulo operator.
class Display implements Runnable {
    int threadId;
    static int v = 1;
    static int higehstId = 0;
    static Object monitor = new Object();

    Display(int id) {
        this.threadId = id;
    }

    public void run() {
        print();
    }

    private void print() {
        while (v < 100) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            synchronized (monitor) {
                if ((v - 1) % higehstId == threadId - 1) {
                    System.out.println(threadId + ":" + v);
                    v++;
                    monitor.notifyAll();
                } else {
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    public static void main(String[] ar) {
        Thread t1 = new Thread(new Display(1));
        Thread t2 = new Thread(new Display(2));
        Thread t3 = new Thread(new Display(3));
        Thread t4 = new Thread(new Display(4));
        Thread t5 = new Thread(new Display(5));
        Display.higehstId = 5;
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

(Multi-Threading Python) Print 1 to 10 numbers alternatively, using two threads


Tag : python , By : firebasket
Date : March 29 2020, 07:55 AM
I hope this helps you . It is rarely useful to have threads move in lockstep with each other. If you really needed them to, you could use two separate events, as alluded to by Prudhvi. For example:
from threading import Thread, Event

event_1 = Event()
event_2 = Event()

def func_1(ev1, ev2):
    for i in range(1, 11, 2):
        ev2.wait()  # wait for the second thread to hand over
        ev2.clear()  # clear the flag
        print('1')
        ev1.set()  # wake the second thread

def func_2(ev1, ev2):
    for i in range(2, 11, 2):
        ev2.set()  # wake the first thread
        ev1.wait()  # wait for the first thread to hand over
        ev1.clear()  # clear the flag
        print('2')

t1 = Thread(target=func_1, args=(event_1, event_2))
t2 = Thread(target=func_2, args=(event_1, event_2))

t1.start()
t2.start()

program to print odd numbers and even numbers on seperate threads


Tag : c , By : LUK
Date : March 29 2020, 07:55 AM

How to create 2 threads and to print Thread id's alternatively and numbers from 1 to 20?


Tag : c , By : firebasket
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?
  • How do I use Java to read from a file that is actively being written to?
  • What code analysis tools do you use for your Java projects?
  • IllegalArgumentException or NullPointerException for a null parameter?
  • How do I configure and communicate with a serial port?
  • What are the different methods to parse strings in Java?
  • Android Broadcastreceiver for other apps install/delete not working
  • Android Studio onClick not working in BindViewHolder
  • How to use Spring Converter for some controllers only?
  • How verify that 3 numbers in sequence are equals?
  • When using .compareTo to compare dates, why doesn't it take Months into account?
  • Does the perfomance of "filter then map" and "map then filter" differ in a Stream?
  • How can I set the initial Delay after pressing the start Button to a specific time (HH:mm:ss) format
  • How to switch between Android devices during the tests
  • How to configure java.util.logging via properties to use standard output?
  • How to iterate through array in order
  • Is there better way of iteration to find the evenly divisible number?
  • How do I avoid using if statements with a large amount of variables in java
  • Writing JUnit test cases for a Spring Boot Service Application with autowired components
  • Cors for GET with Postman not showing headers
  • Printing values in different column same row using APACHE POI
  • Fully decompile java6 web application
  • Passing keycloak configuration parameters in the code rather than reading from application.properties
  • setDataSource() IO exception
  • Unexpected Output while retrieving Data from mongodb and displaying in a csv file?
  • Algorithm for searching a value in two arrays
  • How to avoid casting with generic return values?
  • Java/RegEx - Negation of pattern not working
  • How to split a string to non empty words if it might include a separator like tab on first place
  • Supplier<Sequence<String>> cannot be iterated more than once
  • Why there is only one thread can actually started in @PostConstruct method?
  • Manage CompletionStage inside of Netty handler
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com