473,586 Members | 2,707 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

adding task to list stopping a task getting the result of a task

679 Contributor
Expand|Select|Wrap|Line Numbers
  2. import javax.swing.*;
  3. import java.awt.event.*;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.concurrent.*;
  7. import java.lang.reflect.*;
  9. public class Exec1 extends JFrame implements ActionListener {
  11.   int k = 0;
  12.   int n = 15;
  13.   JTextArea ta = new JTextArea(40,20);
  14.   List<Future> taskList= new ArrayList<Future>();
  15.   Exec1() {
  16.     add(new JScrollPane(ta));
  17.     JPanel p = new JPanel();
  18.     JButton b = new JButton("Start");
  19.     b.addActionListener(this);
  20.     p.add(b);
  21.     b = new JButton("Stop current");
  22.     b.setActionCommand("Stop");
  23.     b.addActionListener(this);
  24.     p.add(b);
  25.     b = new JButton("Curent result");
  26.     b.setActionCommand("Result");
  27.     b.addActionListener(this);
  28.     p.add(b);
  29.     b = new JButton("Shutdown");
  30.     b.addActionListener(this);
  31.     p.add(b);
  32.     b = new JButton("ShutdownNow");
  33.     b.addActionListener(this);
  34.     p.add(b);
  35.     add(p, "South");
  36.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  37.     pack();
  38.     setVisible(true);
  39.   }
  41.   public void actionPerformed(ActionEvent e)  {
  42.     String cmd = e.getActionCommand();
  43.     try {
  44.       Method m = this.getClass().getDeclaredMethod("task"+cmd);
  45.       m.invoke(this);
  46.     } catch(Exception exc) { exc.printStackTrace(); }
  47.   }
  50.   class SumTask implements Callable<Integer> {
  52.     private int taskNum,
  53.                 limit;
  55.     public SumTask(int taskNum, int limit) {
  56.       this.taskNum = taskNum;
  57.       this.limit = limit;
  58.     }
  60.     public Integer call() throws Exception {
  61.       int sum = 0;
  62.       for (int i = 1; i <= limit; i++) {
  63.         if (Thread.currentThread().isInterrupted()) return null;
  64.         sum+=i;
  65.         ta.append("Task " + taskNum + " part result = " + sum + '\n');
  66.         Thread.sleep(1000);
  67.       }
  68.       return sum;
  69.     }
  70.   };
  72.   Future<Integer> task;
  74.   //ExecutorService exec = Executors.newSingleThreadExecutor();
  75.   ExecutorService exec = Executors.newFixedThreadPool(3);
  77.   public void taskStart() {
  78.     try {
  80.       taskList.add(task);
  81.       task = exec.submit(new SumTask(++k, 15));
  82.     } catch(RejectedExecutionException exc) {
  83.         ta.append("Execution rejected\n");
  84.         return;
  85.     }
  86.     ta.append("Task " + k + " submitted\n");
  87.   }
  89.   public void taskResult() {
  91.     for(int i=0;i<taskList.size();i++){
  92.         task=taskList.get(i);
  93.     String msg = "";
  94.     if (task.isCancelled()) msg = "Task cancelled.";
  95.     else if (task.isDone()) {
  96.       try {
  97.         msg = "Ready. Result = " + task.get();
  98.       } catch(Exception exc) {
  99.           msg = exc.getMessage();
  100.       }
  101.     }
  102.     else msg = "Task is running or waiting for execution";
  103.     JOptionPane.showMessageDialog(null, msg);
  104.     }
  105.   }
  107.   public void taskStop() {
  108.     task.cancel(true);
  109.   }
  111.   public void taskShutdown() {
  112.     exec.shutdown();
  113.     ta.append("Executor shutdown\n");
  114.   }
  116.   public void taskShutdownNow() {
  117.     List<Runnable> awaiting = exec.shutdownNow();
  118.     ta.append("Executor shutdown now - awaiting tasks:\n");
  119.     for (Runnable r : awaiting) {
  120.       ta.append(r.getClass().getName()+'\n');
  121.     }
  123.  }
  126.   public static void main(String[] args) {
  127.      new Exec1();
  128.   }
  130. }
i want to add tasks to a list then when a button is clicked stop a task or when another button is clicked show result of a task
when eg taskResult() is called i need to find that task(eg first task) in a list then show the result i dont want to limit the number of tasks(i cd do that with buttons) but i want to have unlimited number of tasks
but how i can get the result of eg 1st task then the second task etc.?
is it possible ? any hints ?
thank you in advance
Apr 24 '07 #1
0 1549

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Mark Preuss | last post by:
Hi all, Anybody seen where if after a Build with errors the Task List won't pop up when you click on the tab? I have to shut down the whole IDE to get it to come up. This is in VS.NET 2003. I don't remember this occuring in version 2002. Thanks, Mark
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and "push_back" a copy of this into a vector V. This is repeated many times in an iterative process. Ok whenever I "push_back" a copy of Class A, I also want...
by: Ben Dewey | last post by:
Project: ---------------------------- I am creating a HTTPS File Transfer App using ASP.NET and C#. I am utilizing ActiveDirectory and windows security to manage the permissions. Why reinvent the wheel, right? Everything so far is working well with the Active Directory. The problem I am having is with adding File Permissions to a...
by: Andrew | last post by:
Hey all, I am very new to ASP.Net (and .Net in general), but that isn't stopping the boss from wanting to begin new projects in it. This latest project has me kinda stumped and after a couple days of struggling, I figure asking you all (the experts) will keep me from going down some dark and dangerous road. The project I have is a fairly...
by: shiry | last post by:
Hi, I need to do some important cleanup before my console application exists. I got some ideas from the groups and I used the console ctrl event. This is working well and it fires for all cases, including the CTRL_CLOSE_EVENT (if I close the application from the X botton). But on the contrary to what the MSDN indicates, ending my process...
by: Marcus | last post by:
Hi, I am a newbie at C#. Here is my current problem: I want my application to iterate through the list of tasks presented in task manager. I want it to look at the task names and if a certain task exist in the task list I want to kill it (as nice as possible). I started the task manager with the following row:...
by: Neo Geshel | last post by:
I have strip-mined, strip-searched, and completely exhausted the Internet (up to the 30th page on Google, with 100 results per page!!), all without finding an answer to my question AS TO WHY IT IS IMPOSSIBLE TO PROGRAMMATICALLY ADD A BUTTON TO A DYNAMICALLY CREATED PAGE. Or, to be more precise, why it is impossible to have an onClick sub ...
by: joanne matthews (RRes-Roth) | last post by:
I'm getting different results when I add up a list of floats depending on the order that I list the floats. For example, the following returns False: def check(): totalProp=0 inputs= for each in inputs: totalProp+=each print "totalProp=",totalProp
by: Bob Jones | last post by:
I have an odd business requirement and I think that the implementation is not correct in the terms of OOP development. Any help on the concepts would be very appreciated! We currently have a custom Page object which is derived from the base Page object. We also have custom controls that derive from a base class that performs custom drawing...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.