Single-threaded (schedule) and multi-threaded (Scheduledexecutorservice) Implement timer task management and query __ concurrent

Source: Internet
Author: User
0, Preface

In the game engineering development process, the timer function is the general game essential function, at the same time, in other types of projects, also often need to use the Timer method. For example, to build a building in the game need to Countdown. The following from the single thread and multithreading two aspects of the implementation of the timer function.
1, single thread (schedule)

First we need a separate time task class, inherited TimerTask, used to represent specific timing tasks, individually proposed to encapsulate into a class, easy to manage and implement:

Import Java.util.TimerTask;
Import Java.util.concurrent.ConcurrentHashMap;
Import Java.util.concurrent.Future;
public class Systemtimertask  extends timertask{
	private long taskid;//task ID
	private Long runtime;// Countdown to the specific time (in seconds)
	private Concurrenthashmap<long, future<long>> Futuremap; 
	Public Systemtimertask (Long Taskid,long runtime) {
		this.taskid = TaskID;
		This.runtime = runtime;
	}
    @Override public
    Void Run () {
    	System.out.println ("Time Remain:" +this.runtime);
    	if (this.runtime--<= 0) {  
            try {  
                future<long> Future = Futuremap.remove (TaskID);  
                Future.cancel (true);  
            finally {  
                System.out.println ("###### Task" +taskid + "is completed!!");
	}} Public long Getremaintime () {return runtime;}
	Public long GetTaskID () {return TaskID}}

In a single-threaded case, you do not need to consider other conditions to call the schedule method directly to implement, the specific invocation method is as follows:

Timer timer = new timer (); 
Systemtimertask () task =  new Systemtimertask (10001,20);

About the schedule method declared as: Schedule (timertask task, long delay, long period)

--task: Scheduled task;

--delay: In milliseconds, indicates that the task is delayed delay milliseconds after execution;

--period: In milliseconds, the duration of the task execution, which is the timer initial value.
2, multithreading (Scheduledexecutorservice) in the actual application development, single-threaded application scope is very narrow, concurrency is an essential factor to be considered in the project development, in the timer implementation, the use of multiple threads, Multiple timer concurrent operations can be implemented more efficiently, while in a large project, it is easier to manage and view scheduled task threads. So, based on the Java built-in Timer task thread pool Scheduledexecutorservice, we encapsulate a timer task thread management class, as follows:

Import Java.util.Iterator;
Import Java.util.concurrent.ConcurrentHashMap;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.TimeUnit; The Systemtimertask is included in the public class Timermanager {    private static timermanager based on the specific package name instance
    ; Private Timermanager () {} public static Timermanager getinstance () {if (instance = = null) {R
        Eturn new Timermanager ();
    return instance;  Private Scheduledexecutorservice service = Executors.newsinglethreadscheduledexecutor (); Initialize the Scheduledexecutorservice thread pool, depending on the situation of the private static Concurrenthashmap<long, systemtimertask> Taskmap = New Concurrenthashmap<long, systemtimertask> ();//Use a hash table with task ID key to store all implemented scheduled Tasks public Boolean starttimer (Long ID,
		Long Time,long InitialDelay, long period, Timeunit unit) {if (Taskmap.containskey (ID)) {return false; else {Systemtimertask Task_time =New Systemtimertask (Id,time);
			This.addtask (ID, task_time);  
	        iterator keys = Taskmap.keyset (). iterator ();  
	            while (Keys.hasnext ()) {Long key = (long) keys.next (); 
	        if (key = = ID) System.out.println ("Whether there is-------------" + (key = = ID) + "ID:" +id); 
			} System.out.println ("Presence of +++++++++++" + taskmap.get (ID). Getremaintime ());
			This.service.scheduleAtFixedRate (Task_time, initialdelay,period, unit);
		return true;
	} public Scheduledexecutorservice GetService () {return service;
	public void Setservice (Scheduledexecutorservice service) {this.service = service; Public long Getremain (long id) {if (This.gettask (). ContainsKey (ID)) {return This.gettask (). Get (ID). getremaintim
		E ();
	else return-1;
	Public Concurrenthashmap<long, Systemtimertask> Gettask () {return taskmap;
	public void AddTask (long id, systemtimertask task1) {taskmap.put (ID, TASK1); }}

The above sets the timer management class to Singleton mode, preventing other objects from instantiating themselves and ensuring that all objects are accessing an instance.

The parameters of the Scheduleatfixedrate method are illustrated with the schedule method in the Timer class above. Can be inspected by oneself.

Here's how to test the main function:

public static void Main (string[] args) throws Interruptedexception {
		long remain = ten;
		Long remain2 =;
		System.out.println ("Start:");
		Long id1 = m;
		Long Id2 = A;
		Timermanager.getinstance (). Starttimer (ID1, remain, 0, 1, timeunit.seconds);
		Timermanager.getinstance (). Starttimer (ID2, remain2, 0, 1, timeunit.seconds);
		Thread.Sleep (3000);
		System.out.println ("exists::::" + timermanager.getinstance (). Gettask (). ContainsKey (ID1));
		System.out.println ("+++++++++++++++++++++time remain ...:" +timermanager.getinstance (). Getremain (ID2) (). ));
	}
3, SummaryIn this paper, based on single thread and multithreading two ways to realize the function of timer, two kinds of advantages and disadvantages, reasonable adoption. At the same time, in the multithreaded implementation, there is a point of inadequacy, in the specific application of the time to correct, that is, the timing task ID can be automatically generated by the growth sequence to ensure its uniqueness, because of the time relationship, this article has not been added.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.