Java FX. Threads, Workers and Tasks

Size: px
Start display at page:

Download "Java FX. Threads, Workers and Tasks"

Transcription

1 Java FX Threads, Workers and Tasks

2 Threads and related topics Lecture Overview...but first lets take a look at a good example of Model - View - Controler set up This and most of the lecture is taken from the Pro JavaFX book: Chapter 6

3 Good Model-View-Controler Example Remember: Model: the data for the program View: the GUI objects Controler: the listeners Seperating these can make a program easier to read or understand to change parts ( you could have a different View)

4 What the program will look like... Example program:

5 MVC Example Setup public class MVCExample extends Application { private Model model; // Model is an inner class private View view; // View is an inner class public static void main(string[ ] args) { Application.launch(args); public MVCExample() { // called by launch( ) model = new Model( ); public void start(stage stage) throws Exception { view = new View(model);...

6 MVC Example Setup public void start(stage stage) throws Exception { view = new View(model); hookupevents( ); stage.settitle("mvc Example"); stage.setscene(view.scene); stage.show(); private void hookupevents() { // add event handlers view.changefillbutton.setonaction(new EventHandler<ActionEvent>() { public void handle(actionevent actionevent) { Paint fillpaint = model.getfillpaint(); if (fillpaint.equals(color.lightgray)) { model.setfillpaint(color.gray);

7 MVC Example Setup private static class Model { private ObjectProperty<Paint> fillpaint = new... private Model( ) { fillpaint.set(color.lightgray); strokepaint.set(color.darkgray); public Paint getfillpaint() { return fillpaint.get(); public ObjectProperty<Paint> fillpaintproperty() { return fillpaint; // end of Model inner class

8 MVC Example Setup private static class View { public Rectangle rectangle; public Button changefillbutton;.. public Scene scene; // create the scene private View(Model model) { rectangle = RectangleBuilder.create().width(200).height(200).build(); rectangle.fillproperty().bind( model.fillpaintproperty() ); rectangle.strokeproperty().bind( model.strokepaintproperty() );

9 MVC Example Setup public class MVCExample extends Application { private Model model; private View view; public static void main(string[ ] args){ this.launch( ); public MVCExample( ) { model = new Model( ); public void start(stage stage) { hookupevents( ); private void hookupevents() { private class Model { private class View { // inner class definitions

10 Good Model-View-Controler Example Remember: Model: the data for the program View: the GUI objects Controler: the listeners Seperating these can make a program easier to read or understand to help organize the program

11 Good Model-View-Controler Example Remember: Model: the data for the program View: the GUI objects Controler: the listeners Seperating these can make a program easier to read or understand to help organize the program You You could could save save an an empty empty version version as as a a template template for for starting starting new new projects projects

12 Example program: Ok, on to an Example...

13 Example program: Ok, on to an Example...

14 Ok, on to Example... private void hookupevents() { view.changefillbutton.setonaction(new EventHandler<ActionEvent>() { public void handle(actionevent actionevent) { final Paint fillpaint = model.getfillpaint(); if (fillpaint.equals(color.lightgray)) { model.setfillpaint(color.gray); else { model.setfillpaint(color.lightgray); ); try { Thread.sleep(Long.MAX_VALUE); catch (InterruptedException e) { // Bad code

15 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree)

16 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree) private void hookupevents( ) { view.changefillbutton.setonaction(new EventHandler<ActionEvent>() { public void handle(actionevent actionevent) {... Thread.sleep(Long.MAX_VALUE); // Bad code is taking all the FX application thread's time );

17 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree) The application thread can do millions of things each second. But..

18 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree) The application thread can do millions of things each second. But if there is a function or process that is taking seconds or even minutes then none of the normal things can be done.

19 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree) The application thread can do millions of things each second. But if there is a function or process that is taking seconds or even minutes then none of the normal things can be done. long database searches getting something from the web long calculation

20 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree) The application thread can do millions of things each second. But if there is a function or process that is taking seconds or even minutes then none of the normal things can be done. long database searches getting something from the web long calculation lab example

21 Creating Helpers for the FX Application Thread Instead of having the application thread work on long functions or process, create some helper threads (like the TA's) Let's step back from Java FX, and take a simple look at Java threads. First, a little background on threads...

22 Multi-Threaded Programming So what is a thread? the flow of execution in a program normally line by line in the code unless we do a loop if statement switch statement fuction call starts with the first line in main...and then goes to the next line

23 Multi-Threading Multi-Threading depending on the number of processors (cpu) Thread 1: main

24 Multi-Threading Multi-Threading depending on the number of processors (cpu) Thread 1: main Thread 2: print Multi-Processor Computer

25 Multi-Threading Multi-Threading depending on the number of processors (cpu) Thread 1: Thread 3: Thread 2: main save print Multi-Processor Computer

26 Multi-Threading Multi-Threading depending on the number of processors (cpu) Thread 1: Thread 3: Thread 2: main save print Multi-Processor Computer Single Processor Computer (time slicing)

27 Multi-Threading Multi-Threading depending on the number of processors (cpu) Thread 1: Thread 3: Thread 2: main save print Multi-Processor Computer Single Processor Computer (time slicing) my winxp with 2 CPUs

28 Multi-Threading Multi-Threading depending on the number of processors (cpu) Thread 1: Thread 3: Thread 2: main save print Multi-Processor Computer Single Processor Computer (time slicing) The JVM and OS will take care of the ugly parts of making this work

29 Making a Thread There are two main ways of creating a thread implement the Runnable interface Runnable <interface> void run( )

30 Making a Thread There are two main ways of creating a thread implement the Runnable interface or create a subclass of Thread class Runnable <interface> void run( ) Thread MyThread

31 Making a Thread There are two main ways of creating a thread implement the Runnable or create a subclass of Thread class Why do we need two ways? Runnable <interface> void run( ) Thread MyThread

32 Making a Thread There are two main ways of creating a thread implement the Runnable or create a subclass of Thread class Why do we need two ways? Runnable <interface> void run( ) Isn't this just going to confuse me? Thread MyThread

33 Making a Thread There are two main ways of creating a thread implement the Runnable or create a subclass of Thread class Why do we need two ways? Runnable <interface> void run( ) this allows us to use another class as our parent Thread MyThread MyParent MyThread

34 Making a Thread First simple example Runnable <interface> void run( ) PrintChars PrintNums

35 PrintChars class PrintChars implements Runnable { private char chartoprint; private int times; public PrintChars(char c, int t) { chartoprint = c; times = t; public void run( ) { for(int i = 0; i < times; i++) System.out.print( chartoprint ); // end of PrintChars class

36 PrintNums class PrintNums implements Runnable { private int lastnum; public PrintNums(int n) { lastnum = n; public void run( ) { for(int i = 1; i <= lastnum; i++) System.out.print( " " + i ); // end of PrintNums class

37 The Main public class TreadDemo { public static void main(string[ ] args){ Runnable printa = new PrintChars('a', 1000); Runnable printz = new PrintChars('z', 1000); Runnable print1000 = new PrintNums( 1000 ); Thread thread1 = new Thread( printa ); Thread thread2 = new Thread( printz ); Thread thread3 = new Thread( print1000 ); thread1.start(); thread2.start(); thread3.start(); // end of main // creates the new thread from the OS // end of ThreadDemo class

38 The Program Output aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...

39 there there is is no no quarantee quarantee The Program Output aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa about aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa about the the order order that that the aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa the threads threads will will run run in in aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (z's aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (z's were were started started aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa before before num's) num's) aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

40 there there is is no no quarantee quarantee The Program Output aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa about aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa about the the order order that that the aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa the threads threads will will run run in in aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (z's aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (z's were were started started aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa before before num's) num's) aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz by default zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa the thread run aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa order aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz the OS controls

41 Making a Thread There are two main ways of creating a thread implement the Runnable or create a subclass of Thread class Runnable <interface> void run( ) Thread PrintChars PrintNums

42 Changing PrintChars to a Thread class PrintChars extends Thread { private char chartoprint; private int times; public PrintChars(char c, int t) { chartoprint = c; times = t; public void run( ) { // still need to override the run method for(int i = 0; i < times; i++) System.out.print( chartoprint ); // end of PrintChars class

43 Changes to Main public class TreadDemo { public static void main(string[ ] args){ // Runnable printa = new PrintChars('a', 1000); // Runnable printz = new PrintChars('z', 1000); // Runnable print1000 = new PrintNums( 1000 ); // Thread thread1 = new Thread( printa ); Thread thread1 = new PrintChars('a', 1000); Thread thread2 = new PrintChars('z', 1000); Thread thread3 = new PrintNums( 1000 ); thread1.start( ); thread2.start( ); thread3.start( ); // end of main // end of ThreadDemo class

44 Run vs Start Run: this is where the execution of the thread will start (kind of like main in a class) Start: create a new thread and call the run method Runnable <interface> void run( ) Thread void start( ) PrintChars PrintNums

45 Changes to Main public class TreadDemo { public static void main(string[ ] args){ Thread thread1 = new PrintChars('a', 1000); Thread thread2 = new PrintChars('z', 1000); Thread thread3 = new PrintNums( 1000 ); thread1.run( ); thread2.run( ); thread3.run( ); // end of main What What will will happen happen here? here? // end of ThreadDemo class

46 Changes to Main public class TreadDemo { public static void main(string[ ] args){ Thread thread1 = new PrintChars('a', 1000); Thread thread2 = new PrintChars('z', 1000); Thread thread3 = new PrintNums( 1000 ); thread1.run( ); thread2.run( ); thread3.run( ); // end of main main thread of execution:

47 Changes to Main public class TreadDemo { public static void main(string[ ] args){ Thread thread1 = new PrintChars('a', 1000); Thread thread2 = new PrintChars('z', 1000); Thread thread3 = new PrintNums( 1000 ); thread1.run( ); thread2.run( ); thread3.run( ); // end of main main thread of execution: thread1.run

48 Changes to Main public class TreadDemo { public static void main(string[ ] args){ Thread thread1 = new PrintChars('a', 1000); Thread thread2 = new PrintChars('z', 1000); Thread thread3 = new PrintNums( 1000 ); run run is is just just a a normal normal function function call call thread1.run( ); thread2.run( ); thread3.run( ); // end of main No No new new threads threads are are create create main thread2.run thread of execution: thread1.run

49 Fixing our problem by adding new helper thread private void hookupevents() { view.changefillbutton.setonaction( new EventHandler<AEvent>( ) { public void handle(actionevent actionevent) { final Paint fillpaint = model.getfillpaint( ); if (fillpaint.equals(color.lightgray)) { model.setfillpaint(color.gray); Runnable task = new Runnable() { // simulates long process public void run() { Thread.sleep(10000); Platform.runLater(new Runnable() { public void run() { final Rectangle rect = view.rectangle; double newarcsize = rect.getarcheight() < 20? 30 : 0; rect.setarcwidth(newarcsize); rect.setarcheight(newarcsize); ; new Thread(task).start();

50 Fixing our problem by adding new helper thread private void hookupevents() { view.changefillbutton.setonaction( new EventHandler<AEvent>( ) { public void handle(actionevent actionevent) { final Paint fillpaint = model.getfillpaint( ); if (fillpaint.equals(color.lightgray)) { model.setfillpaint(color.gray); Runnable task = new Runnable() { // simulates long process public void run() { Thread.sleep(10000); Platform.runLater(new Runnable() { public void run() { final Rectangle rect = view.rectangle; ; new Thread(task).start(); who is this? double newarcsize = rect.getarcheight() < 20? 30 : 0; rect.setarcwidth(newarcsize); rect.setarcheight(newarcsize);

51 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree) Only the Application thread can change the scene graph. - the scene graph is not thread safe ( only one thread allowed)

52 JavaFX Application Thread JavaFX Application thread is responsible for all event handling updating of bindings making changes to the scene graph (tree) Only the Application thread can change the scene graph. - the scene graph is not thread safe ( only one thread allowed) Platform.runLater( runnable ); \\ ask the application thread to \\ run this when it gets time

53 Fixing our problem by adding new helper thread private void hookupevents() { view.changefillbutton.setonaction( new EventHandler<AEvent>( ) { public void handle(actionevent actionevent) { final Paint fillpaint = model.getfillpaint( ); if (fillpaint.equals(color.lightgray)) { model.setfillpaint(color.gray); Runnable task = new Runnable() { // simulates long process public void run() { Thread.sleep(10000); Platform.runLater(new Runnable() { public void run() { final Rectangle rect = view.rectangle; ; new Thread(task).start(); who is this? double newarcsize = rect.getarcheight() < 20? 30 : 0; rect.setarcwidth(newarcsize); our new thread rect.setarcheight(newarcsize); will give some work back to the Aplication thread

54 Other FX Helpers Worker: an interface that defines some functions for a thread doing some work. These functions return readonly properties that can update the scene graph Task<V>: an abstract class that implements the Worker interface. A Task should be used for one-time tasks. The abstact function is where you can do the work abstract public V call( ) throws Exception;

55 Worker interface Contains read-only properties that can be used to update the scene graph title : string for the title of the task running: boolean for if the task is running or not state: READY, SCHEDULED, RUNNING, SUCCEEDED, CANCELLED, FAILED totalwork: double how much work for task workdone: double amount of work already completed progress: double percentage of workdone / totalwork value: Object the output from the task exception: Object exception thrown when FAILED

56 Task<V> Has the following functions (and more) V call( ); boolean cancel( ); where you do the work to shut down the task Update functions that update the Worker void updatetitle( String ); void updatemessage( String ); void updateprogress( long workdone, long totalwork);

57 Using a Task to update a Progress Bar Creating a Task object that will: update the progress bar with the task's progress property update the window's title with the task's title property

58 public void start(stage stage) throws Exception { Task<String> worker = new Task<String>() { protected String call() throws Exception { int total = 100; updatetitle("simple Task Example"); updateprogress(0, total); for (int i = 1; i <= total; i++) { try { Thread.sleep(1000); catch (InterruptedException e) { Using a Task to update a Progress Bar ; updatetitle("simple Task Example(" + i + ")"); updateprogress(i, total); updatetitle("simple Task Example Completed"); return "Completed";

59 public void start(stage stage) throws Exception { Task<String> worker = new Task<String>() { protected String call() throws Exception { int total = 100; updatetitle("simple Task Example"); updateprogress(0, total); for (int i = 1; i <= total; i++) { try { Thread.sleep(1000); catch (InterruptedException e) { Using a Task to update a Progress Bar ; updatetitle("simple Task Example(" + i + ")"); updateprogress(i, total); updatetitle("simple Task Example Completed"); return "Completed";

60 Using a Task to update a Progress Bar // create Task object ProgressBar progressbar = new ProgressBar( ); progressbar.progressproperty().bind( worker.progressproperty()); AnchorPane anchorpane = new AnchorPane(); AnchorPane.setBottomAnchor(progressBar, 20.0); AnchorPane.setRightAnchor(progressBar, 20.0); AnchorPane.setLeftAnchor(progressBar, 20.0); anchorpane.getchildren().add(progressbar); stage.titleproperty().bind(worker.titleproperty()); stage.setscene(new Scene(anchorPane, 400, 100)); new Thread( worker ).start(); stage.show();

61 Task<String> worker = new Task<String>() { protected String call() throws Exception { ; int total = 100; updatetitle("start"); updateprogress(0, total); for (int i = 1; i <= total; i++) { // do something updatemessage(.); updateprogress(i, total); updatetitle("completed"); return "Completed"; Using atask to do something

62 Task<V> worker = new Task<V>() { protected V call() throws Exception { int total = 100; updatetitle("start"); updateprogress(0, total); for (int i = 1; i <= total; i++) { // do something ; updatemessage(.); updateprogress(i, total); updatetitle("completed"); return V.variable(); Using atask to do something -make a calculation -retrieve from database -access on web

63 Task<V> worker = new Task<V>() { protected V call() throws Exception { int total = 100; updatetitle("start"); updateprogress(0, total); for (int i = 1; i <= total; i++) { // do something ; updatemessage(.); updateprogress(i, total); updatetitle("completed"); return VTYPEvariable; Using atask to do something -make a calculation -retrieve from database -access on web V is the object that is the result of your work

64 Task<Void> worker = new Task<Void>() { protected Void call() throws Exception { ; int total = 100; updatetitle("start"); updateprogress(0, total); for (int i = 1; i <= total; i++) { // do something updatemessage(.); updateprogress(i, total); updatetitle("completed"); return null; Using atask to do something -make a calculation -retrieve from database -access on web V is the object that is the result of your work or could be null

65 public void start(stage stage) throws Exception { Task<String> worker = new Task<String>() { protected String call() throws Exception { int total = 100; updatetitle("simple Task Example"); updateprogress(0, total); for (int i = 1; i <= total; i++) { try { Thread.sleep(1000); catch (InterruptedException e) { Using a Task to update a Progress Bar ; updatetitle("simple Task Example(" + i + ")"); updateprogress(i, total); updatetitle("simple Task Example Completed"); return "Completed";

66 Book example of using a Task An Example of all the properties of a Worker

67 JavaFX Application Thread REMEMBER: Only the Application thread can change the scene graph. - the scene graph is not thread safe ( only one thread allowed) After a Task finishes, the task could ask the Application to update the scene by using: Platform.runLater( runnable ); \\ ask the application thread to \\ run this when it gets time or Bind Properties from the scene to properties in the Task

68 Extra Free Information: Thread Pools if your program will create and use many threads, then you may want to use a Thread Pool. A Thread Pool will create threads when needed and reuse these threads when possible rather than creating new ones. ExecutorServices pool = Executors.newCachedThreadPool();. pool.execute( mytask ); // will create or reuse threads. pool.execute( mytask2 );

69

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University Threads & Timers CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 Multi-tasking When you re working, how many different applications do you have open at one

More information

Single processor CPU. Memory I/O

Single processor CPU. Memory I/O Lec 17 Threads Single processor CPU Memory I/O Multi processes Eclipse PPT iclicker Multi processor CPU CPU Memory I/O Multi-core Core Core Core Core Processor Memory I/O Logical Cores Multi-threaded

More information

Event-Driven Programming with GUIs. Slides derived (or copied) from slides created by Rick Mercer for CSc 335

Event-Driven Programming with GUIs. Slides derived (or copied) from slides created by Rick Mercer for CSc 335 Event-Driven Programming with GUIs Slides derived (or copied) from slides created by Rick Mercer for CSc 335 Event Driven GUIs A Graphical User Interface (GUI) presents a graphical view of an application

More information

Lecture 10 Multithreading

Lecture 10 Multithreading Lecture 10 Multithreading Introduction to Threads Threads in Java public class TaskThreadDemo public static void main(string[] args) // Create tasks Runnable printa = new PrintChar('a', 100); Runnable

More information

Concurrency in JavaFX. Tecniche di Programmazione A.A. 2014/2015

Concurrency in JavaFX. Tecniche di Programmazione A.A. 2014/2015 Concurrency in JavaFX Tecniche di Programmazione Summary 1. The problem 2. javafx.concurrent package 2 The problem Concurrency in JavaFX UI Responsiveness JavaFX is single threaded The JavaFX application

More information

Multithread Computing

Multithread Computing Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread

More information

Java FX. Properties and Bindings

Java FX. Properties and Bindings Java FX Properties and Bindings Properties : something that holds data data can be simple like an int or complex like a list data structure this data can be used to update other things when it changes

More information

CST242 Concurrency Page 1

CST242 Concurrency Page 1 CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor

More information

CON Visualising GC with JavaFX Ben Evans James Gough

CON Visualising GC with JavaFX Ben Evans James Gough CON6265 - Visualising GC with JavaFX Ben Evans (@kittylyst) James Gough (@javajimlondon) Who are these guys anyway? Beginnings This story, as with so many others, starts with beer... Beginnings It was

More information

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar JAVA CONCURRENCY FRAMEWORK Kaushik Kanetkar Old days One CPU, executing one single program at a time No overlap of work/processes Lots of slack time CPU not completely utilized What is Concurrency Concurrency

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Concurrent Computing CSCI 201 Principles of Software Development

Concurrent Computing CSCI 201 Principles of Software Development Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

Multithreading and Interactive Programs

Multithreading and Interactive Programs Multithreading and Interactive Programs CS160: User Interfaces John Canny. This time Multithreading for interactivity need and risks Some design patterns for multithreaded programs Debugging multithreaded

More information

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi

More information

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Note: Each loop has 5 iterations in the ThreeLoopTest program. Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called

More information

Composite Pattern Diagram. Explanation. JavaFX Subclass Hierarchy, cont. JavaFX: Node. JavaFX Layout Classes. Top-Level Containers 10/12/2018

Composite Pattern Diagram. Explanation. JavaFX Subclass Hierarchy, cont. JavaFX: Node. JavaFX Layout Classes. Top-Level Containers 10/12/2018 Explanation Component has Operation( ), which is a method that applies to all components, whether composite or leaf. There are generally many operations. Component also has composite methods: Add( ), Remove(

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

CSCI 201L Written Exam #1 Fall % of course grade

CSCI 201L Written Exam #1 Fall % of course grade Final Score /15 Name SOLUTION ID Extra Credit /0.5 Lecture Section (circle one): TTh 8:00-9:20 TTh 9:30-10:50 TTh 11:00-12:20 CSCI 201L Written Exam #1 Fall 2017 15% of course grade The exam is one hour

More information

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1) Advanced Programming Methods Lecture 6 - Concurrency in Java (1) Overview Introduction Java threads Java.util.concurrent References NOTE: The slides are based on the following free tutorials. You may want

More information

Swinging from the Outside

Swinging from the Outside Swinging from the Outside A guide to navigating Swing from the outside of Sun Brian Mason, Dir Software of Engineering, Teseda S295599 Space is big, really big. You might think it is a long way down to

More information

1. (5 points) In your own words, describe what an instance is.

1. (5 points) In your own words, describe what an instance is. SE1021 Exam 2 Name: 1. (5 points) In your own words, describe what an instance is. 2. (5 points) Consider the Apple class in the UML diagram on the right. Write a couple lines of code to call the instance

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

Multimedia-Programmierung Übung 3

Multimedia-Programmierung Übung 3 Multimedia-Programmierung Übung 3 Ludwig-Maximilians-Universität München Sommersemester 2015 JavaFX Version 8 What is JavaFX? Recommended UI-Toolkit for Java 8 Applications (like e.g.: Swing, AWT) Current

More information

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006 This document provides a brief introduction to programming with threads in Java. I presume familiarity

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming http://www.motifake.com/multi-tasking-baby-dishes-bath-wash-demotivational-posters-118837.html Traditional Multi-tasking - One CPU - Many users, each wishing to use a computer

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void

More information

Object Oriented Programming. Week 10 Part 1 Threads

Object Oriented Programming. Week 10 Part 1 Threads Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that

More information

CS 112 Programming 2. Lecture 14. Event-Driven Programming & Animations (1) Chapter 15 Event-Driven Programming and Animations

CS 112 Programming 2. Lecture 14. Event-Driven Programming & Animations (1) Chapter 15 Event-Driven Programming and Animations CS 112 Programming 2 Lecture 14 Event-Driven Programming & Animations (1) Chapter 15 Event-Driven Programming and Animations rights reserved. 2 Motivations Suppose you want to write a GUI program that

More information

User Space Multithreading. Computer Science, University of Warwick

User Space Multithreading. Computer Science, University of Warwick User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing

More information

Animation Part 2: MoveableShape interface & Multithreading

Animation Part 2: MoveableShape interface & Multithreading Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

GUI Output. Adapted from slides by Michelle Strout with some slides from Rick Mercer. CSc 210

GUI Output. Adapted from slides by Michelle Strout with some slides from Rick Mercer. CSc 210 GUI Output Adapted from slides by Michelle Strout with some slides from Rick Mercer CSc 210 GUI (Graphical User Interface) We all use GUI s every day Text interfaces great for testing and debugging Infants

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming http://www.motifake.com/multi-tasking-baby-dishes-bath-wash-demotivational-posters-118837.html http://thechive.com/2014/01/15/champions-of-multitasking-35-photos/ www.funscrape.com/meme/62260

More information

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) M257 MTA Spring2010 Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) 1. If we need various objects that are similar in structure, but

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

Software Practice 3 Today s lecture Today s Task

Software Practice 3 Today s lecture Today s Task 1 Software Practice 3 Today s lecture Today s Task Prof. Hwansoo Han T.A. Jeonghwan Park 43 2 MULTITHREAD IN ANDROID 3 Activity and Service before midterm after midterm 4 Java Thread Thread is an execution

More information

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory

More information

CS 556 Distributed Systems

CS 556 Distributed Systems CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that

More information

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment.

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment. Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment Overview What constitutes a thread? Instruction pointer Stack space

More information

Throughout the exam, write concisely and underline key words or phrases. Have fun! Exam 2. Week 7 (Winter 2013). Dr. Yoder. Sec 031.

Throughout the exam, write concisely and underline key words or phrases. Have fun! Exam 2. Week 7 (Winter 2013). Dr. Yoder. Sec 031. SE1021 Exam 2 Name: You may have an 8.5x11 note sheet for this exam. No calculators or other study aids on this exam. Write your initials at the tops of the following pages and read through the exam before

More information

THREADS AND CONCURRENCY

THREADS AND CONCURRENCY THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on

More information

Java Programming Lecture 7

Java Programming Lecture 7 Java Programming Lecture 7 Alice E. Fischer Feb 16, 2015 Java Programming - L7... 1/16 Class Derivation Interfaces Examples Java Programming - L7... 2/16 Purpose of Derivation Class derivation is used

More information

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public

More information

Computational Expression

Computational Expression Computational Expression Graphics Janyl Jumadinova 6 February, 2019 Janyl Jumadinova Computational Expression 6 February, 2019 1 / 11 Java Graphics Graphics can be simple or complex, but they are just

More information

shared objects monitors run() Runnable start()

shared objects monitors run() Runnable start() Thread Lecture 18 Threads A thread is a smallest unit of execution Each thread has its own call stack for methods being invoked, their arguments and local variables. Each virtual machine instance has at

More information

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 5 problems on the following 7 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

CSCI 201L Written Exam #1 Fall % of course grade

CSCI 201L Written Exam #1 Fall % of course grade Name Final Score /15 ID Extra Credit /0.5 Lecture Section (circle one): TTh 8:00-9:20 TTh 9:30-10:50 TTh 11:00-12:20 CSCI 201L Fall 2017 15% of course grade The exam is one hour and 50 minutes and is closed

More information

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created

More information

Building a Java First-Person Shooter

Building a Java First-Person Shooter Building a Java First-Person Shooter Episode 2 [Last update: 4/30/2017] Objectives This episode adds the basic elements of our game loop to the program. In addition, it introduces the concept of threads.

More information

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other

More information

CS108, Stanford Handout #22. Thread 3 GUI

CS108, Stanford Handout #22. Thread 3 GUI CS108, Stanford Handout #22 Winter, 2006-07 Nick Parlante Thread 3 GUI GUIs and Threading Problem: Swing vs. Threads How to integrate the Swing/GUI/drawing system with threads? Problem: The GUI system

More information

Software Practice 1 - Multithreading

Software Practice 1 - Multithreading Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee

More information

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

More information

Java Foundations. 9-1 Introduction to JavaFX. Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Java Foundations. 9-1 Introduction to JavaFX. Copyright 2014, Oracle and/or its affiliates. All rights reserved. Java Foundations 9-1 Copyright 2014, Oracle and/or its affiliates. All rights reserved. Objectives This lesson covers the following objectives: Create a JavaFX project Explain the components of the default

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 27/04/2018 Sorry for the delay in getting slides for today 2 Another reason for the delay: Yesterday: 63 posts on the course Piazza yesterday. A7: If you received 100 for correctness (perhaps minus a late

More information

Requirements. PA4: Multi-thread File Downloader Page 1. Assignment

Requirements. PA4: Multi-thread File Downloader Page 1. Assignment PA4: Multi-thread File Downloader Page 1 Assignment What to Submit Write a program that downloads a file from the Internet using multiple threads. The application has a Graphical Interface written in JavaFX,

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 2.2] GUI FRAMEWORKS & CONCURRENCY 1 GUI FRAMEWORKS & CONCURRENCY Once upon a time GUI applications

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

More information

In this lab we will practice creating, throwing and handling exceptions.

In this lab we will practice creating, throwing and handling exceptions. Lab 5 Exceptions Exceptions indicate that a program has encountered an unforeseen problem. While some problems place programmers at fault (for example, using an index that is outside the boundaries of

More information

System Programming. Practical Session 4: Threads and Concurrency / Safety

System Programming. Practical Session 4: Threads and Concurrency / Safety System Programming Practical Session 4: Threads and Concurrency / Safety Using Threads - All the computer programs you've seen so far were sequential only one thing was performed at any given time - Sometimes

More information

Java s Implementation of Concurrency, and how to use it in our applications.

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

46 Advanced Java for Bioinformatics, WS 17/18, D. Huson, December 21, 2017

46 Advanced Java for Bioinformatics, WS 17/18, D. Huson, December 21, 2017 46 Advanced Java for Bioinformatics, WS 17/18, D. Huson, December 21, 2017 11 FXML and CSS A program intended for interactive use may provide a large number of user interface (UI) components, as shown

More information

Event-driven Programming, Separation of Concerns, the Observer pattern and the JavaFX Event Infrastructure

Event-driven Programming, Separation of Concerns, the Observer pattern and the JavaFX Event Infrastructure Java GUIs in JavaFX Event-driven Programming, Separation of Concerns, the Observer pattern and the JavaFX Event Infrastructure 1 GUIs process inputs and deliver outputs for a computing system Inputs Click

More information

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY Instructors: Crista Lopes Copyright Instructors. Basics Concurrent Programming More than one thing at a time Examples: Network server handling hundreds of clients

More information

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07 Informatica 3 Marcello Restelli 9/15/07 10/29/07 Laurea in Ingegneria Informatica Politecnico di Milano Structuring the Computation Control flow can be obtained through control structure at instruction

More information

Services. service: A background task used by an app.

Services. service: A background task used by an app. CS 193A Services This document is copyright (C) Marty Stepp and Stanford Computer Science. Licensed under Creative Commons Attribution 2.5 License. All rights reserved. Services service: A background task

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical

More information

Parallel & Concurrent Programming

Parallel & Concurrent Programming Program Parallel & Concurrent Programming CSCI 334 Stephen Freund Memory Count Words A.html Count cow: cow:28 moo: moo:3 the: the:35 wombat: wombat:16 purple: purple:3

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,

More information

Lecture 03: Thread API (continue)

Lecture 03: Thread API (continue) Lecture 03: Thread API (continue) SSC2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Lecture 03 1 Recap Extending Thread or implementing Runnable Thread terminology Stopping Threads

More information

Game Engineering: 2D

Game Engineering: 2D Game Engineering: 2D CS420-2013S-19 Introduction to Threading David Galles Department of Computer Science University of San Francisco -0: Parallel Programming Xbox has 3 cores, each of which has 2 hardware

More information

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

Lecture 35. Threads. Reading for next time: Big Java What is a Thread? Lecture 35 Threads Reading for next time: Big Java 21.4 What is a Thread? Imagine a Java program that is reading large files over the Internet from several different servers (or getting data from several

More information

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer. Exception Handling General idea Checked vs. unchecked exceptions Semantics of throws try-catch Example from text: DataAnalyzer Exceptions [Bono] 1 Announcements Lab this week is based on the textbook example

More information

Contents. 6-1 Copyright (c) N. Afshartous

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar Design Patterns MSc in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie)! Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

ITCertMaster. Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way!

ITCertMaster.  Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way! ITCertMaster Safe, simple and fast. 100% Pass guarantee! http://www.itcertmaster.com Exam : 1z1-809 Title : Java SE 8 Programmer II Vendor : Oracle Version : DEMO Get Latest & Valid 1z1-809 Exam's Question

More information

IT In the News. Login tokens have been reset for those affected and vulnerabilities have been fixed. o Vulnerabilities existed since July 2017

IT In the News. Login tokens have been reset for those affected and vulnerabilities have been fixed. o Vulnerabilities existed since July 2017 IT In the News 50 million Facebook accounts were affected by a security breach two weeks ago Attacks exploited bugs in Facebook s View As feature (built to give users more privacy) and a feature that allowed

More information

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

Threads, Concurrency, and Parallelism

Threads, Concurrency, and Parallelism Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start

More information

Chapter 15 Event-Driven Programming and Animations

Chapter 15 Event-Driven Programming and Animations Chapter 15 Event-Driven Programming and Animations 1 Motivations Suppose you want to write a GUI program that lets the user enter a loan amount, annual interest rate, and number of years and click the

More information

Threads. Fundamentals of Computer Science

Threads. Fundamentals of Computer Science Threads Fundamentals of Computer Science Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually at the same time (multiple cores) Why? Get work

More information

2.6 Error, exception and event handling

2.6 Error, exception and event handling 2.6 Error, exception and event handling There are conditions that have to be fulfilled by a program that sometimes are not fulfilled, which causes a so-called program error. When an error occurs usually

More information

Chapter 19 Multithreading

Chapter 19 Multithreading Chapter 19 Multithreading Prerequisites for Part VI Chapter 14 Applets, Images, and Audio Chapter 19 Multithreading Chapter 20 Internationalization 1 Objectives To understand the concept of multithreading

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

1 interface TemperatureSensor extends java.rmi.remote 2 { 3 public double gettemperature() throws java.rmi.remoteexception; 4 public void

1 interface TemperatureSensor extends java.rmi.remote 2 { 3 public double gettemperature() throws java.rmi.remoteexception; 4 public void 1 interface TemperatureSensor extends java.rmi.remote 2 { 3 public double gettemperature() throws java.rmi.remoteexception; 4 public void addtemperaturelistener ( TemperatureListener listener ) 5 throws

More information

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization COMP 213 Advanced Object-oriented Programming Lecture 23 Shared Variables and Synchronization Communicating Threads In the previous lecture, we saw an example of a multi-threaded program where three threads

More information

Tommy Färnqvist, IDA, Linköping University

Tommy Färnqvist, IDA, Linköping University Lecture 4 Threads and Networking in Java TDDC32 Lecture notes in Design and Implementation of a Software Module in Java 23 January 2013 Tommy Färnqvist, IDA, Linköping University 4.1 Lecture Topics Contents

More information

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that

More information

GlobalLogic Technical Question Paper

GlobalLogic Technical Question Paper GlobalLogic Technical Question Paper What is the output of the following code when compiled and run? Select two correct answers. public class Question01 { public static void main(string[] args){ int y=0;

More information