Thread: Definition
A thread (control) is a list of instructions executed sequentially by a program. The threads of a program share the same address space. Although separate stack and local variables, global variables share. Threads are "light" in the sense that the creation, destruction and synchronization are relatively inexpensive by sharing address space. The reasons to organize a program in a number of threads can be manifold:
- Some programs are written simply, especially the collections of loosely related tasks (ie, largely independent).
- Interactive programs are more efficient service where the input or the output display are organized into separate threads.
- The programs are potentially parallelizable architecture on multi-processor or multi-core processors.
- The problem at hand requires parts of the program in asynchronous communication between them.
- E 'practicable to impose a modular code.
I / O non-blocking
One of the strong motivations for the Concurrent programming using threads is to achieve non-blocking service for Input / Output. When the application needs to perform an I / O, you should not hang, so that other operations that do not depend on us the / O can be performed. A technique for managing I / O non-blocking, which is used for example in the microcontrollers used in the board for physical computing, is the polling , ie the verification of what cycling event on a set of input devices. The cyclical nature of polling is controlled by a timer. The I / O can be achieved using non-blocking threads. The reading of a certain device can be assigned to a thread which is blocked waiting for data. The other thread, which does not depend on the reading of the data, they can proceed concurrently.
Activity Diagrams
The following code invokes the processing method
print ()
object cl
class Class1
.
class Class1 {void print () {for (int i = 0; i <100; i + +) println ("yep");}} void setup () {Class1 cl = new Class1 (); cl.stampa ();}
Thread
, then you can proceed to the activation of a secondary thread by invoking the method start ()
. The code should be rewritten as
class Class2 extends Thread {void run () {for (int i = 0; i <100; i + +) println ("yep");}} void setup () {cl = new Class2 Class2 (); cl.start () ;}
print ()
now called run ()
. The method start ()
exists in the superclass of Class 2
(in class Thread
, and deals with the invocation of the method run ()
. This time, the processing flow, shown in Figure 2 has two threads.NOTE:
There is a second way to declare and set up a thread , by implementing the interfaceRunnable
Java. And 'you must use this mode if you want to activate a new thread on an object of a class that has already been declared as an extension of another class.Thread: Service
EXAMPLE 1: Time-Thread
The class
Thread
has a method sleep ()
which puts it in was blocked for a number of milliseconds. This allows you to program in a compact and smooth flow of events mutually independent. For example, the following code produces a drawing of two ellipses of different colors and each color corresponds to a different time interval (ie, 1000 and 1300 milliseconds) between two subsequent events of the drawing.
TimerThread class extends Thread {int timediff, / / how much time with color; TimerThread (color c, int td) {td = timediff, col = c;} void run () {while (true) {fill (col); try { ellipse (int (random (100)), int (random (100)), int (random (20)), int (random (20))) sleep (timediff);} catch (Exception e) {println (" Exception in sleep ");}}}} void setup () {TimerThread TT1 = new TimerThread (color (120,120,0), 1000); TimerThread TT2 = new TimerThread (color (0,120,120), 1300); tt1.start () ; tt2.start ();} void draw () {}
sleep ()
calls to Java to be invoked inside an try catch ()
, ie a section of code that allows the capture of the exceptions. Theexception handling allows you to address the conditions that alter the normal flow of program execution. In the example, the sleep ()
may fail and raise ( throw
) an exception that, in this case is handled just by writing a message on the console.EXERCISE 1
It should be added to the code of Example 1 a class that deals with the background repainted at regular intervals, so as to avoid overlapping of ellipses.
I / O non-blocking thread-based
When the interactive object needs to read or write from / to files, devices, or network socket , it is appropriate that it does not completely block waiting for data. With threads, this is elegantly solved by activating a separate thread that handles asynchronous I / O, and locks where necessary.
EXAMPLE 2: Reading keyboard commands
Suppose you need to draw automatically and repeated ellipses in the graphics window, and you want to control the attributes of these ellipses using keywords entered by the keyboard. Should separate the task of reading and interpreting (parsing) the character stream that comes from the keyboard from the task of producing graphical output.This can be done as follows, in the simple case in which the words accepted are "red", "green", and "blue" corresponding to different coloratura ellipses produced.
Stdin StringBuffer, boolean online; color color; void keyReleased () {char c = key; if (c! = '\ n') {stdin.append (c);} else line = true;} class extends Thread {String ColorInput results; char c; void run () {while (true) {if (line) {println (stdout); stdin.toString results = (); stdin.setLength (0); line = false; if (results.equals ( "red")) {color = color (255, 0, 0);} if (results.equals ("green")) {color = color (0, 255, 0);} if (results.equals ("blue ")) {color = color (0, 0, 255);}} try {sleep (5), / / cpu to relief from the active waiting} catch (Exception e) {println (" Exception in sleep ");} TimerThread}}} class extends Thread {int timediff, / / as time TimerThread (int td) {td = timediff;} void run () {while (true) {try {fill (color), ellipse (int (random (100 )), int (random (100)), int (random (20)), int (random (20))) sleep (timediff);} catch (Exception e) {println ("Exception in sleep");} }}} void setup () {stdin = new StringBuffer (); TimerThread TT1 = new TimerThread (100); ColorInput us ColorInput = new (); ci.start (); tt1.start ();} void draw () { }
Thread
. The first extension is an active waiting lines of text, setting the color whenever it encounters a line of text containing one of three key words recognized. The invocation of sleep (5)
makes this less expensive active waiting for the CPU. The other thread, however, is responsible for drawing ellipses ten per second. In Processing is difficult to achieve a blocking input from the keyboard, since it is not directly accessible stream System.in
, where in Java you can normally apply reading buffered blocker.Conversely, processing calls for a programming event-based providing the event handler keyReleased ()
, keyPressed ()
, and keyTyped ()
. E 'can still do a blocking input of a line from a text file with code like
try {BufferedReader stdiin createReader = ("filename") println (stdiin.readLine ());} catch (Exception e) {}
createReader ()
is a function of processing that creates a BufferedReader
object from a file or a URL. It allows a slight simplification compared to Java code
try {is = new FileReader FileReader ("filename"); BufferedReader stdiin = new BufferedReader (is); println (stdiin.readLine ());} catch (Exception e) {}
loadStrings ()
, which loads all the lines of text file into an array of typeString []
. This method can be useful if the file is too large or dynamically variable.EXERCISE 2
The following code performs the periodic reading of a line of text from a text generator site. It extends by adding a thread that displays these sentences on the window graphics with animated typography.
sentenceReader class extends Thread {int timediff, / / how much time sentenceReader (int td) {td = timediff;} void run () {while (true) {try {BufferedReader stdiin createReader = ("http://www.essl.at / cgi-bin/swrap/cgis/lexikon-orakel.pl ") for (int i = 0; i <13; i + +) stdiin.readLine (), println (stdiin.readLine ()); sleep (timediff); } catch (Exception e) {}}}} void setup () {st = new sentenceReader sentenceReader (2000); st.start ();} void draw () {}
Synchronization
Suppose you need to extend the reading of keyboard commands with two threads that take commands from
stdin
. Commands can be consumed by one or other of the thread, but the same command can not be consumed by both. In this case you may have problems of race condition , ie configurations of shared code that give rise to results of sequence-dependentscheduling attributed to different thread. In particular, the critical section
stdin.toString results = (); stdin.setLength (0); line = false;
synchronized
. In this case, we can introduce a class with synchronized methods:
class IO extends Thread {String results; synchronized String acquire () {results = stdin.toString (); line = false; stdin.setLength (0); return (results);}}
sampling ()
must be synchronized to avoid inconsistencies in the presence of multiple samples, as can be done by co-owners of the same account. Synchronization of threads is a complex subject for the study of which there are specialist books .EXERCISE 3
Reference
Chapter 9 of the book Visualizing Data - Ben Fry, O'Reilly 2007 acquisition provides examples of asynchronous data from files and from remote sites, with the use of threads and synchronization.
No comments:
Post a Comment