Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

thread java timer

import java.util.Timer;
import java.util.TimerTask;

public class Test {

    static int counter = 0;
    static Timer timer;

    public static void main(String[] args) {

        //create timer task to increment counter
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                // System.out.println("TimerTask executing counter is: " + counter);
                counter++;
            }
        };

        //create thread to print counter value
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        System.out.println("Thread reading counter is: " + counter);
                        if (counter == 3) {
                            System.out.println("Counter has reached 3 now will terminate");
                            timer.cancel();//end the timer
                            break;//end this loop
                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        timer = new Timer("MyTimer");//create a new timer
        timer.scheduleAtFixedRate(timerTask, 30, 3000);//start timer in 30ms to increment  counter

        t.start();//start thread to display counter
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: Java try...catch block 
Java :: icon share android 
Java :: jpa page sort 
Java :: java super keyword 
Java :: how to create an array without knowing the size java 
Java :: java boucle for 
Java :: how to create xml file in java 
Java :: float.compare java 
Java :: findone in spring boot 2.4.1 
Java :: how to concatenate two strings in java 
Java :: add two variables in Java 
Java :: how to output in java 
Java :: Array List java can I add a pair of element 
Java :: dockerfile for spring boot app 
Java :: get intersection of two lists java 
Java :: how to disable screenshot in react native 
Java :: write file java 
Java :: java set classpath 
Java :: and roid shape setCornerRadii 
Java :: java.lang.NoClassDefFoundError: 
Java :: java anonmyous array eg 
Java :: generate random number in java within a range without repeating with android studio 
Java :: startactivity not working in android adapter 
Java :: spring mvc project example 
Java :: .jar window immediately closes on doubleclick 
Java :: algorithm to know if a number is an integer 
Java :: Read File and Resource in JUnit Test into Stream 
Java :: java make object 
Java :: how to code java??????????? 
Java :: has been compiled by a more recent version of the Java Runtime (class file version 55.0) 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =