logo
down
shadow

Move to main thread after another thread go to sleep


Move to main thread after another thread go to sleep

By : Abhishek Kumar
Date : December 01 2020, 04:50 PM
it should still fix some issue What you have done in your code above created a thread that runs concurrently with the main thread. What actually happens is:
Main thread starts and initiates AutoUpdater thread The two threads will run concurrently. In fact, the Main thread may even terminate before the AutoUpdater thread has really started. The auto-update thread processes the clients ONCE, then sleeps for 24 hours and then terminates and your program completely terminates at this point.
code :
public class AutoUpdater implements Runnable {
    public void run() {
        while (true) {
            try {
                System.out.println("Thread is running...");
                for (int i = 0; i < clients.size(); i++) {
                    // do something...
                }
            } finally {
                System.out.println("Thread ended.\n");
            }

            int time = 1000 * 60 * 60 * 24;
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                System.out.println("Something interrputed thread while running.");
            }
        }
    }
}
public class AutoUpdater implements Runnable {
    public void run() {
        System.out.println("Thread is running...");
        for (int i = 0; i < clients.size(); i++) {
            // do something...
        }
        System.out.println("Thread ended.\n");
    }
}

public static class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(
                    new AutoUpdater(clients, lock.writeLock()),
                    0,
                    24,
                    TimeUnit.HOURS);

        System.out.println("This is a test");
    }
}
Object sharedMonitor = new byte[0]

// In your auto-updater and other threads
synchronised(sharedMonitor ) {

}
public static class Main {
    private static List<String> clients = new ArrayList<>();

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ReadWriteLock lock = new ReentrantReadWriteLock();

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(
                new AutoUpdater(clients, lock.writeLock()),
                0,
                24,
                TimeUnit.HOURS);

        Lock readLock = lock.readLock();
        while (true) {
            try {
                readLock.lock();
                System.out.println("This is a test");
            } finally {
                readLock.unlock();
            }
        }
    }
}
public class AutoUpdater implements Runnable {
    public void run() {
        try {
            lock.lock();
            System.out.println("Thread is running...");
                // do something...
            }
        } finally {
            System.out.println("Thread ended.\n");
            lock.unlock();
        }
    }
}


Share : facebook icon twitter icon
C++ UNIX: Threading: Make Main-Thread wait or sleep until processing is over - main-thread doesnt know pthread_t refrenc

C++ UNIX: Threading: Make Main-Thread wait or sleep until processing is over - main-thread doesnt know pthread_t refrenc


By : user3553036
Date : March 29 2020, 07:55 AM
will help you sc->start_server runs an endless loop in which a MyClass processing method is invoked in a thread. How can i replace the while(true) statement in main so that my program waits for all threads to terminate? , Use join on any thread you want to wait.
sleep() thread is sleeping main thread and not separate specified thread

sleep() thread is sleeping main thread and not separate specified thread


By : Diego Hernández
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , As i can see you already know Thread.sleep is static method and only sleeps the current thread running there are 2 places where you are using sleep().
BackgroundTestRunnerThread.sleep(sleepTime * 1000); in run() method:This can not be an issue as it will be always called in BackgroundTestRunnerThread thread not in main thread. pause(int milliseconds) method: I can not see your main thread code but chances are you are calling the pause method from main assuming it will sleep the BackgroundTestRunnerThread thread but because it might be getting called from main thread it will make main thread sleep not the other one.
c# Thread.sleep sleep the current thread or the main thread?

c# Thread.sleep sleep the current thread or the main thread?


By : Large Generators
Date : March 29 2020, 07:55 AM
wish helps you Thread.Sleep() sleeps the current thread. Here is the msdn documentation:
Thread.Sleep
If there's only one thread running(main) and sleep(1000) is invoked, will the thread sleep for exactly 1 second or atlea

If there's only one thread running(main) and sleep(1000) is invoked, will the thread sleep for exactly 1 second or atlea


By : iansealy
Date : March 29 2020, 07:55 AM
it should still fix some issue Approximately 1-second pause. The thread can be woken up beforehand and you'll get an InterruptedException, or the thread can sleep for 1000ms and then not get to run immediately, so it will be 1000ms + microseconds (or more, if there are higher priority threads hogging the CPU).
You're also calling it wrong. It's Thread.sleep(1000);, as a static method it always acts on the current thread and you can't make other threads sleep with it.
Sleep method on child Thread causing Main Thread to sleep as well

Sleep method on child Thread causing Main Thread to sleep as well


By : Ruben de Groot
Date : March 29 2020, 07:55 AM
I hope this helps . The Thread.sleep(long) javadoc says (emphasis added)
Related Posts Related Posts :
  • 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 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
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org