<< Chapter < Page Chapter >> Page >

Il codice che segue effettua la lettura periodica di una linea di testo da un sito generatore di testo. Lo siestenda aggiungendo un thread che visualizza queste frasi sulla finestra grafica con animazione tipografica. class sentenceReader extends Thread{ int timediff; // quanto temporalesentenceReader(int td) {timediff = td; }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() {sentenceReader st = new sentenceReader(2000); st.start();} void draw() {}

Sincronizzazione

Si supponga di dover estendere la lettura di comandi da tastiera con due thread che prendono comandi da stdin . I comandi possono essere consumati dall'uno o dall'altro dei thread, ma uno stessocomando non può essere consumato da entrambi. In questo caso si possono presentare problemi di race condition , cioè configurazioni di codice concorrente che danno luogo a risultati dipendenti dalla sequenza di scheduling attribuita ai vari thread. In particolare, la sezione critica results=stdin.toString(); stdin.setLength(0);linea = false; può dare luogo a comportamenti inconsistenti se interrotta dallo scheduler per passare il controllo dall'uno all'altro thread. Questi problemi si possonorisolvere imponendo la non interrompibilità delle sezioni critiche di codice, per mezzo della parola chiave synchronized . Nella fattispecie, si può introdurre una classe con metodi sincronizzati: class IO extends Thread { String results;synchronized String acquire() { results=stdin.toString();linea = false; stdin.setLength(0);return(results); }} I metodi invocati su un oggetto di questa classe non sono interrompibili da metodi invocati sullo stesso oggetto. In ambito ditransazioni bancarie, per esempio, un metodo prelievo() dovrà essere sincronizzato per evitare inconsistenze in presenza di prelievi multipli, come possono essere effettuati da co-titolari dellostesso conto. La sincronizzazione di thread è un argomento complesso, per l'approfondimento del quale esistono libri specializzati .

Si estenda la lettura di comandi da tastiera con due thread che prendono comandi da stdin .

Nel codice seguente si noti l'uso della getName() per stampare il nome del thread interessato. StringBuffer stdin; boolean linea;color colore; IO io = new IO();void keyReleased() { char c = key;if (c!='\n') { stdin.append(c);} else linea=true;} class IO extends Thread {String results; synchronized String acquire() {results=stdin.toString(); linea = false;stdin.setLength(0); return(results);} }class ColorInput extends Thread { String results;char c;void ColorInput (IO inout) { io = inout;} void run() {while(true) { if (linea) {results=io.acquire(); println(this.getName() + results);if (results.equals("rosso")) { colore = color(255, 0, 0);} if (results.equals("verde")) {colore = color(0, 255, 0); }if (results.equals("blu")) { colore = color(0, 0, 255);} }try { sleep(2); // to relief the cpu from active waiting} catch (Exception e) {println("Exception in sleep");} }} }class TimerThread extends Thread{ int timediff; // quanto temporaleTimerThread(int td) {timediff = td; }void run() {while(true) { try {fill(colore); 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 ci = new ColorInput();ColorInput ci2 = new ColorInput(); ci.start(); ci2.start();tt1.start(); }void draw() { }

Reference

Il capitolo 9 del libro Visualizing Data -- Ben Fry; O'Really 2007 fornisce esempi di acquisizione asincrona di dati da file e da sitiremoti, con l'utilizzazione di thread e di sincronizzazione.

Questions & Answers

what is microbiology
Agebe Reply
What is a cell
Odelana Reply
what is cell
Mohammed
how does Neisseria cause meningitis
Nyibol Reply
what is microbiologist
Muhammad Reply
what is errata
Muhammad
is the branch of biology that deals with the study of microorganisms.
Ntefuni Reply
What is microbiology
Mercy Reply
studies of microbes
Louisiaste
when we takee the specimen which lumbar,spin,
Ziyad Reply
How bacteria create energy to survive?
Muhamad Reply
Bacteria doesn't produce energy they are dependent upon their substrate in case of lack of nutrients they are able to make spores which helps them to sustain in harsh environments
_Adnan
But not all bacteria make spores, l mean Eukaryotic cells have Mitochondria which acts as powerhouse for them, since bacteria don't have it, what is the substitution for it?
Muhamad
they make spores
Louisiaste
what is sporadic nd endemic, epidemic
Aminu Reply
the significance of food webs for disease transmission
Abreham
food webs brings about an infection as an individual depends on number of diseased foods or carriers dully.
Mark
explain assimilatory nitrate reduction
Esinniobiwa Reply
Assimilatory nitrate reduction is a process that occurs in some microorganisms, such as bacteria and archaea, in which nitrate (NO3-) is reduced to nitrite (NO2-), and then further reduced to ammonia (NH3).
Elkana
This process is called assimilatory nitrate reduction because the nitrogen that is produced is incorporated in the cells of microorganisms where it can be used in the synthesis of amino acids and other nitrogen products
Elkana
Examples of thermophilic organisms
Shu Reply
Give Examples of thermophilic organisms
Shu
advantages of normal Flora to the host
Micheal Reply
Prevent foreign microbes to the host
Abubakar
they provide healthier benefits to their hosts
ayesha
They are friends to host only when Host immune system is strong and become enemies when the host immune system is weakened . very bad relationship!
Mark
what is cell
faisal Reply
cell is the smallest unit of life
Fauziya
cell is the smallest unit of life
Akanni
ok
Innocent
cell is the structural and functional unit of life
Hasan
is the fundamental units of Life
Musa
what are emergency diseases
Micheal Reply
There are nothing like emergency disease but there are some common medical emergency which can occur simultaneously like Bleeding,heart attack,Breathing difficulties,severe pain heart stock.Hope you will get my point .Have a nice day ❣️
_Adnan
define infection ,prevention and control
Innocent
I think infection prevention and control is the avoidance of all things we do that gives out break of infections and promotion of health practices that promote life
Lubega
Heyy Lubega hussein where are u from?
_Adnan
en français
Adama
which site have a normal flora
ESTHER Reply
Many sites of the body have it Skin Nasal cavity Oral cavity Gastro intestinal tract
Safaa
skin
Asiina
skin,Oral,Nasal,GIt
Sadik
How can Commensal can Bacteria change into pathogen?
Sadik
How can Commensal Bacteria change into pathogen?
Sadik
all
Tesfaye
by fussion
Asiina
what are the advantages of normal Flora to the host
Micheal
what are the ways of control and prevention of nosocomial infection in the hospital
Micheal
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Programmazione di artefatti interattivi. OpenStax CNX. Dec 09, 2010 Download for free at http://cnx.org/content/col10417/1.9
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Programmazione di artefatti interattivi' conversation and receive update notifications?

Ask