class MyThread extends Thread {
public void run() {
System.out.println("Helló, ez itt a" + getName() + " Thread" );
}
}
public class ExtendedThread {
static public void main(String args[]) {
MyThread a, b;
a = new MyThread();
b = new MyThread();
a.start();
b.start();
}
}
A teljes forrás: ExtendedThread.java
|
class MyThread implements Runnable {
public void run() {
System.out.println("Helló, ez itt a " +
Thread.currentThread().getName() + " Thread" );
}
}
public class RunnableThread {
static public void main(String s[]) {
MyThread work2do;
Thread a, b;
work2do = new MyThread();
a = new Thread(work2do);
b = new Thread(work2do);
a.start();
b.start();
}
}
A teljes forrás: RunnableThread.java
|
Logo Applet külön szálban
// Runnable interfész alkalmazása Applet-ben
import java.awt.*;
public class Logo extends java.applet.Applet implements Runnable {
Image img; // kép handler
Thread thd = null; // a szál
int i = 0; // sor mutató
int imgWidth; // kép szélesség
int imgHeight; // kép magasság
static String imgName; // kép file neve
public void run() { // a runnable run() metódusát felülírjuk
Thread en = Thread.currentThread();
if ((imgName = getParameter("imagefile")) == null)
System.exit(-1);
img = getImage(getCodeBase(), imgName);
repaint();
try {Thread.sleep(500);} catch (InterruptedException e){}
imgWidth = img.getWidth(this);
imgHeight = img.getHeight(this);
if (img != null) {
while (thd == en) {
for (i=0; i<imgHeight; i+=4 ) {
repaint();
try {Thread.sleep(100);} catch (InterruptedException e){}
}
}
}
}
public void update(Graphics g) {
if (img != null) {
g.clearRect(0, 0, imgWidth, imgHeight );
g.clipRect(0, 0, imgWidth, i);
g.drawImage(img, 0, i - imgHeight, null);
g.setClip(0, i, imgWidth, imgHeight-i);
g.drawImage(img, 0, i, null);
showStatus( "Name:"+imgName+", Size:"+imgHeight+"x" +imgWidth );
}
}
public void start() { // Az Applet start, ahol
if (thd == null) { // ha még nincs szál,
thd = new Thread(this); // létrehozzuk
thd.start(); // és elindítjuk
}
}
public void stop() { // Az Applet stop, ahol
thd = null; // jelezzük, hogy vége
} // a szálnak
}
A teljes forrás: Logo.java <hr> <h3>Logo Applet külön szálban</h3> <applet code="Logo.class" height=200 width=300> <param name=imagefile value=javaLogo.gif> </applet> <hr>A HTML forrás: Logo.html |
DigiClock
// Runnable implementációja
import java.awt.Image;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Color;
import java.util.Date;
public class DigiClock extends java.applet.Applet implements Runnable {
// ...
public void start() { // A szál max. prioritáson
if (timer == null) { // fut, hiszen pontosnak kell
timer = new Thread(this); // lennie
timer.setPriority(Thread.MAX_PRIORITY);
timer.start();
}
}
public void stop() {
timer = null;
}
public void run() {
long now, // ciklus belépési pillanat
waiting, // mennyit kell várni (korrig)
updateTime = 0; // "a köv. másodperc"
Date time; // a dátum, idő lekérése
int ora, perc; // segédváltozók
while (timer != null) {
if ( (updateTime += 1000) < (now = System.currentTimeMillis()) )
updateTime = now;
time = new Date();
ora = Integer.parseInt( time.toString().substring(11,13) );
perc = Integer.parseInt( time.toString().substring(14,16) );
mp = Integer.parseInt( time.toString().substring(17,19) );
// Számjegyekre bontás
ora1 = szamjegyek[ora / 10];
ora2 = szamjegyek[ora % 10];
perc1 = szamjegyek[perc / 10];
perc2 = szamjegyek[perc % 10];
repaint(); // kiírás és korrigálás
if ((waiting = updateTime - System.currentTimeMillis()) > 0) {
try {
timer.sleep( waiting );
} catch (InterruptedException e) {}
}
}
}
// ...
}
A teljes forrás: DigiClock.java <hr> <h3> DigiClock </h3> <applet code="DigiClock.class" height=100 width=100> </applet> <hr>A HTML forrás: DigiClock.html |
// Szálcsoport infok
class Szal extends Thread {
Szal(String name) { super(name); } // nevét is eltároljuk
public void run() { // nem csinál semmi
try { // különöset
for (int i=0; i<5; i++)
sleep(100);
} catch (InterruptedException e) {}
}
}
public class SzalCsoport1 {
public static void main(String args[]) {
Szal[] sok_szal = new Szal[15]; // a létrehozandó szálak
for (int i=0; i<15; i++) // mindet installáljuk,
sok_szal[i] = new Szal(i + ". szál");
for (int i=0; i<5; i++) // de csak 5-öt indítunk el
sok_szal[2*i].start();
ThreadGroup aktCsop = Thread.currentThread().getThreadGroup();
int instNum = aktCsop.activeCount(); // csoportban levők
Thread[] th = new Thread[instNum]; // referenciákhoz
int futok = aktCsop.enumerate(th); // a futók lekérdezése és
// megszámlálása
System.out.println("Nyomkövetési info:"); // a nyomkövetési lista
aktCsop.list(); // kiírása
System.out.println("Csoport Név: " + aktCsop.getName());
System.out.println("Példány #: " + instNum);
System.out.println("Futók #: " + futok);
System.out.println("Futók listája");
for (int i=0; i<futok; i++)
System.out.println("\t"+i+". szál: "+th[i].getName());
}
}
A teljes forrás: SzalCsoport1.java
|
// A Szálcsopotot mint egészt kezelő
// setMaxPriority metódusra példa
public class SzalCsoport2 {
public static void main(String[] args) {
ThreadGroup csop = new ThreadGroup("Normal prioritású csop.");
Thread th = new Thread(csop, "Max priotitású szál");
th.setPriority(Thread.MAX_PRIORITY); // Max prioritásra a szálat
csop.setMaxPriority(Thread.NORM_PRIORITY); // Normálra(5) a csop. MAXját
System.out.println("Csop MAX: " + csop.getMaxPriority());
System.out.println("szál MAX: " +th.getPriority());
}
}
A teljes forrás: SzalCsoport2.java
|
// Szálak egyszeri megszakítása
class Szal extends Thread {
Szal(ThreadGroup tg, String name) { super(tg, name); }
public void run() {
try {
while (true) {
System.out.print(getName() + "-fut\t");
sleep(400);
}
} catch (InterruptedException e) {}
}
}
public class SzalCsoport3 {
public static void main(String args[]) {
int i;
ThreadGroup csop = new ThreadGroup("seged"),
thisGr = Thread.currentThread().getThreadGroup();
Szal[] szalak = new Szal[4];
for (i=0; i<4; i++)
szalak[i] = new Szal(csop, i + ". szál");
System.out.println("Fo csoport: " + thisGr.getName() +
", Szál#: " + thisGr.activeCount());
System.out.println("Csop.: " + csop.getName() +
", Szál#: " + csop.activeCount());
for (i=0; i<4; i++)
szalak[i].start();
try { Thread.sleep(1800); } catch(InterruptedException e) {}
System.out.println("interrupt!!!");
csop.interrupt();
}
}
A teljes forrás: SzalCsoport3.java
|
// ThreadLocalTest.java
import java.util.Date;
// Ez lesz az az osztály, ami példányosítva tartalmazza a
// szálankénti objektumot (itt éppen egy egyedi dátum)
class MyThreadLocal extends ThreadLocal {
protected Object initialValue() { // ezt átírva adjuk az
Date d = new Date(); // új értéket
System.out.println("\tThreadLocal initialValue-> " +
d.toString().substring(11,19));
return d;
}
}
// Az osztály minden szála külön tl értéket kap példányosításkor
class Show extends Thread {
static private MyThreadLocal lokal_id = new MyThreadLocal();
Show(String name) {
super(name);
System.out.println(getName() + " konstruktora= " +
lokal_id.get().toString().substring(11,19));
}
public void run() {
for (int i=0; i<6; i++) {
System.out.println(getName() + "= " +
lokal_id.get().toString().substring(11,19) );
try { Thread.sleep(900); } catch (InterruptedException e) {}
}
}
}
public class ThreadLocalTest {
static public void main(String args[]) {
System.out.println("Néhány Show objektum létrehozása");
Show a = new Show("a szál");
Show b = new Show("b szál");
Show c = new Show("c szál");
a.start(); try { Thread.sleep(1000); } catch (InterruptedException e) {}
b.start(); try { Thread.sleep(2000); } catch (InterruptedException e) {}
c.start();
}
}
A teljes forrás: ThreadLocalTest.java
|
// Felfüggesztés a Java 2-ben
class MyThread extends Thread {
volatile boolean threadSuspended; // Igaz, ha a szál suspend állapotba kerül
public void run() {
for (int i=0; i<10; i++) {
System.out.println("Helló, itt a " + getName() + "Thread" );
try {
sleep(500); // várakozás
if (threadSuspended) { // Optimalizálva csak akkor
synchronized(this) { // várunk, ha suspend állapot
while (threadSuspended) // A wait miatt szinkronizált
wait(); // blokkba kerül
}
}
} catch (InterruptedException e) {} // A wait és a sleep is azonos
} // kivételt eredményez
// egyéb tevékenység...
}
public synchronized void mySuspend() { // A változó értéke szerint
if (!threadSuspended) // bekap. a susp. állapotot
System.out.println("Suspend " + getName());// az igazi várakozás a run()
threadSuspended = true; // metódusban van
}
public synchronized void myResume() {
if (threadSuspended) { // Ha éppen suspend állapotban
System.out.println("Resume " + getName());
threadSuspended = false; // van, elengedjük, ill. egy
notify(); // jelzést adunk, hogy resumed!
}
}
}
public class SusRes {
static public void main(String args[]) {
MyThread a, b;
a = new MyThread(); // Két szálat definiálunk
b = new MyThread();
System.out.println("Starting... ");
a.start(); // és indítunk el
b.start();
// Várunk egy kicsit, majd
try { Thread.sleep(2000); } catch (InterruptedException e) {}
a.mySuspend(); // az egyiket felfüggesztjük
// Várjuk a hatást, hogy csak
try { Thread.sleep(1500); } catch (InterruptedException e) {}
// a másik fut tovább
a.myResume(); // Majd ismét elengedjük
}
}
A teljes forrás: SusRes.java
|
Felfüggesztés a Java 1.2-ben a Runnable interfésszel
// Felfüggesztés példa a Java 2-ben
// Példa Runnable interfésszel
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.lang.Math;
public class SusRes1 extends Applet implements Runnable, MouseListener {
int akt = 0; // a karikán melyik pont piros aktuálisan
Thread runner = null; // a szál, amelyik a pontokat rajzolja
volatile boolean threadSuspended; // felfüggesztett-e a szál (egér miatt)
public void init() {
threadSuspended = false;
setFont(new Font("TimesRoman", Font.BOLD, 12)); // a szöveg kiíráshoz
addMouseListener(this); // egér kezelése miatt
}
public void destroy() { // befejezésnél az egér-
removeMouseListener(this); // kezelő leállítása
}
public void start() {
runner = new Thread(this); // Az applet indításakor a
runner.start(); // szálat is elindítjuk
}
public synchronized void stop() { // Az applet leállításakor a
runner = null; // szálnak stop jelzés
if (threadSuspended) { // Ha éppen felfüggesztett
threadSuspended = false; // volt, akkor elengedjük
notify();
}
}
public void run() {
Thread me = Thread.currentThread(); // Amíg a szál él,
while (runner == me) { // addig fut a run() metódus
try {
Thread.sleep(200);
if (threadSuspended) // Ha felfüggesztett,
synchronized(this) {
while (threadSuspended) { // akkor vár, amíg el nem
wait(); // eresztik
}
}
} catch (InterruptedException e){
}
repaint(); // kirajzoljuk az appletet
}
}
// ...
}
A teljes forrás: SusRes1.java <hr> <h3>Felfüggesztés a Java 1.2-ben a Runnable interfésszel</h3> <applet code="SusRes1.class" width=200 height=200> </applet> <hr>A HTML forrás: SusRes1.html |
Felfüggesztés a Java 1.2-ben egy Thread osztállyal
// Felfüggesztés a Java 2-ben
// Thread osztály öröklésével
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.lang.Math;
class Karika extends Thread {
// ...
// A szál biztonságos leállításához (nem felfüggesztett állaotban hagyva)
// Nem része a standard Thread osztálynak!
public synchronized void stopp() {
runner = null;
if (threadSuspended) { // Ha éppen felfüggesztett
threadSuspended = false; // volt, akkor elengedjük
notify();
}
}
public void run() {
Thread me = Thread.currentThread(); // Amíg a szál él,
while (runner == me) { // addig fut a run() metódus
try {
sleep(st); // st ideig alszik
if (threadSuspended) // Ha felfüggesztett,
synchronized(this) {
while (threadSuspended) { // akkor vár, amíg el nem
wait(); // eresztik
}
}
} catch (InterruptedException e){
}
repaint(); // kirajzoljuk az appletet
}
}
// A szál felfüggesztésénél ezt az új metódust hívják meg a főprogram
// mint neve is mutatja, teljesen úgy működik, mint a pause gomb a magnón
// Nem része a standard Thread osztálynak!
public synchronized void pause() { // Váltunk a szál
threadSuspended = !threadSuspended; // felfüggesztési állapotán
if (!threadSuspended) // ha eddig felfügg. volt
notify(); // akkor most eleresztjük
}
// ...
}
public class SusRes2 extends Applet implements MouseListener {
// ...
public void start() {
bal = new Karika(getGraphics(), 70,100, 200); // egyik és másik
jobb = new Karika(getGraphics(), 200,100, 300); // karika példány
bal.start(); jobb.start();
}
// ...
public void stop() { // Az Applet leállásakor
bal.stopp(); // A szálakat is leállítjuk
jobb.stopp(); // egy speciális metódussal
}
public void destroy() { // befejezésnél az egér-
removeMouseListener(this); // kezelő leállítása
}
// ...
}
A teljes forrás: SusRes2.java <hr> <h3>Felfüggesztés a Java 1.2-ben egy Thread osztállyal</h3> <applet code="SusRes2.class" width=300 height=200> </applet> <hr>A HTML forrás: SusRes2.html |
//Interrupt-ot bemutató program
class MyThread extends Thread {
public void run() {
for (int i=0; i<10; i++)
try {
System.out.println("Várok fél másodpercet... [" + i + "]");
sleep(500);
} catch (InterruptedException e) { // amint kiváltódik, kiírjuk
System.out.println("Kivétel a run()-ban: " + e.getMessage());
}
}
}
public class Interrupt {
public static void main(String[] args) {
MyThread a;
a = new MyThread();
System.out.println("Indítás...");
a.start();
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("Szál megszakítása");
a.interrupt();
System.out.println("Meg van szakítva?" + a.isInterrupted());
try { Thread.sleep(1000); } catch (InterruptedException e) {}
// Várakozunk, de mivel kivétel teljesülése törölte a flag-et,
// már csak false értéket kapunk
System.out.println("Meg van szakitva?" + a.isInterrupted());
}
}
A teljes forrás: Interrupt.java
|
// Runnable interfész alkalmazása Applet-ben
import java.awt.*;
public class Logo extends java.applet.Applet implements Runnable {
Image img; // kép handler
Thread thd = null; // a szál
int i = 0; // sor mutató
int imgWidth; // kép szélesség
int imgHeight; // kép magasság
static String imgName; // kép file neve
public void run() { // a runnable run() metódusát felülírjuk
Thread en = Thread.currentThread();
if ((imgName = getParameter("imagefile")) == null)
System.exit(-1);
img = getImage(getCodeBase(), imgName);
repaint();
try {Thread.sleep(500);} catch (InterruptedException e){}
imgWidth = img.getWidth(this);
imgHeight = img.getHeight(this);
if (img != null) {
while (thd == en) {
for (i=0; i<imgHeight; i+=4 ) {
repaint();
try {Thread.sleep(100);} catch (InterruptedException e){}
}
}
}
}
// ...
public void start() { // Az Applet start, ahol
if (thd == null) { // ha még nincs szál,
thd = new Thread(this); // létrehozzuk
thd.start(); // és elindítjuk
}
}
public void stop() { // Az Applet stop, ahol
Thread th2 = thd;
thd = null; // jelezzük, hogy vége
th2.interrupt();
} // a szálnak
}
A teljes forrás: LogoJav.java
|
//Egy lehetséges megoldás a stop() helyettesítésére
class MyStoppingThread extends Thread {
private volatile boolean isRunning = true; //fut-e a szál
public void stopp() { //A standard stop() helyettesítése
isRunning = false; //Már nem fut...
}
public void run() {
while ( isRunning ) { //Csak amíg le nem llítjuk a stopp() metódussal
System.out.println("Helló, ez itt a " + getName());
try { sleep(500); } catch (InterruptedException e) {}
}
}
}
public class StopThread1 {
public static void main(String[] args) {
MyStoppingThread a;
a = new MyStoppingThread();
System.out.println("Indítás...");
a.start();
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("Stop...");
a.stopp();
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("Vége...");
}
}
A teljes forrás: StopThread1.java
|
//Lehet Thread hivatkozással is
class MyStoppingThread extends Thread {
private volatile Thread running_id = this;
public void stopp() { // a leállásnál jelezzük, hogy már nem kell
running_id = null; // a referencia null-ra állítva
}
public void run() {
while ( running_id == this ) { // futhat-e még a szál
System.out.println("Helló, ez itt a " + getName());
try { sleep(300); } catch (InterruptedException e) {}
}
}
}
public class StopThread2 {
public static void main(String[] args) {
MyStoppingThread a;
a = new MyStoppingThread();
System.out.println("Indítás...");
a.start();
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("Stop thread");
a.stopp();
System.out.println("The End");
}
}
A teljes forrás: StopThread2.java
|
// DaemonThread.java
class Daemon extends Thread { // Démon szál osztálya
public void run() { // végtelen ciklusban
while (true) { // fut
System.out.println( getName() + " démon? " + isDaemon() );
try { sleep(500); } catch (InterruptedException e) {}
}
}
}
class Regular extends Thread { // Általános szál
volatile boolean mehet = true;
public void run() {
while (mehet) { // fut, amíg csak kell
System.out.println( getName() + " démon? " + isDaemon() );
try { sleep(500); } catch (InterruptedException e) {}
}
}
public void eleg() { mehet = false; } // leállítja a szálat
}
public class DaemonThread {
static public void main(String s[]) {
Regular a; // szabályos szál
Daemon b; // démon szál
a = new Regular();
b = new Daemon();
System.out.println("Szálak indítása");
a.start(); // indítás,
b.setDaemon(true); b.start(); // démon beállítás
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("A sima szál(ak) leálítása");
a.eleg(); // az általános leáll
}
}
A teljes forrás: DaemonThread.java
|
// Join teszt
class MyThread extends Thread {
public void run() {
System.out.println( getName() + " fut" );
for (int i=0; i<5; i++) {
try { sleep(500); } catch (InterruptedException e) {}
System.out.println( "Helló, itt a " + getName() );
}
System.out.println( getName() + "befejeződött" );
}
}
class MyThread2 extends Thread {
private Thread wait4me;
MyThread2(Thread target) { // Átadjuk a szálat,
super();
wait4me = target; // amire várunk
}
public void run() {
System.out.println( getName() + " várakozik " +
wait4me.getName() + "-ra");
try { wait4me.join(); } catch (InterruptedException e) {}
for (int i=0; i<5; i++) {
try { sleep(500); } catch (InterruptedException e) {}
System.out.println( "Helló, itt a " + getName() );
}
}
}
public class JoinTest {
static public void main(String args[]) {
MyThread a;
MyThread2 b;
a = new MyThread();
b = new MyThread2( a );
b.start();
a.start();
}
}
A teljes forrás: JoinTest.java
|
// Nyomtatoszerüség, join demo
import java.util.Vector;
import java.io.*;
class Tomb { // "Spool" helyett
static Vector tomb = new Vector(10);
public static void put(String s) { tomb.add(s); }
public static Vector get() { return tomb; }
}
class Spooler extends Thread { // a várakoztató szál
String fn;
Spooler(String name) { fn = name; } // file amit feldolgoz
public void run() {
int c;
String s = "";
try {
FileReader f = new FileReader(fn);
while ((c = f.read()) != -1) { // karakterenként olvassuk
if (c == 13) {
Tomb.put(s); // soronként a spoolba írjuk
s = "";
System.out.println();
}
else if (c != 10) {
s = s + (char) c;
}
System.out.print("."); // csak hogy lássuk, hogy
sleep(10); // dolgozik (alszik)
}
f.close();
}
catch (IOException ioe) {}
catch (InterruptedException ine) {}
System.out.println();
}
}
class NyomtatoSzal extends Thread { // Nyomtató, ami a spoolerre
public void run() { // vár
Spooler spooler;
spooler = new Spooler("Nyomtat.java");
System.out.print("Spool keszites elinditasa");
spooler.start(); // spooling,
try { // fő rész
spooler.join(); // megvárjuk a spoolert
System.out.print("Kész a spool, lehet nyomtatni");
// Nyomtatás
Vector v = Tomb.get(); // átveszi a nyomtatandót
for (int i=0; i<v.size(); i++)
System.out.println(v.get(i)); // "nyomtatás"
} catch (InterruptedException e) {}
}
}
public class Nyomtat {
public static void main(String args[]) {
NyomtatoSzal ny = new NyomtatoSzal();
ny.start();
}
}
A teljes forrás: Nyomtat.java
|
// Prioritások vizsgálata
class MyThread extends Thread {
boolean running = true;
MyThread(String name) {
super(name);
}
public void stopp() { running = false; }
public void run() {
while (running) {
System.out.println( getName() );
yield();
}
}
}
public class Priority {
static public void main(String s[]) {
MyThread a, b, c;
int var = 50;
a = new MyThread("Athread");
b = new MyThread("Bthread");
c = new MyThread("Cthread");
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
System.out.println("Start... " +
a.getPriority()+","+b.getPriority()+","+c.getPriority());
a.start(); b.start(); c.start();
// ...
}
}
A teljes forrás: Priority.java
|
// Időosztás vizsgálat
class MyThread extends Thread {
int count=0;
public int getCount() {
return(count);
}
public void run() {
while (true)
count++;
}
}
public class TimeSlice {
static public void main(String s[]) {
MyThread a, b;
int threshold;
a = new MyThread(); b = new MyThread();
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
System.out.println("Starting...");
a.start(); b.start();
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("Stopping...");
a.stop(); b.stop();
System.out.println("Thread a" + a.getCount());
System.out.println("Thread b" + b.getCount());
if (a.getCount() > b.getCount() )
threshold = (int) (a.getCount() * .2);
else
threshold = (int) (b.getCount() * .2);
if (a.getCount() >= b.getCount() - threshold &&
a.getCount() <= b.getCount() + threshold)
System.out.println("A rendszer valószínuleg időosztásos");
else
System.out.println("A rendszer NEM időosztásos");
}
}
A teljes forrás: TimeSlice.java
|
// Egyszerű számláló példa hibás kiírással
public class SimpleCount1 extends Thread {
static int n = 1; // Osztály szintű számláló
public void run() {
for (int i=1; i<=4; i++) {
System.out.print(n + " "); // kiírjuk, majd
n++; // növeljük
}
}
public static void main(String args[]) {
Thread thr1 = new SimpleCount1(), // Két szálat létrehozunk,
thr2 = new SimpleCount1();
thr1.start(); // majd elindítunk
thr2.start();
}
}
A teljes forrás: SimpleCount1.java
|
// Race Condition alap probléma
import java.io.*;
class LogIro { // A kritikus rész
private FileWriter logfile;
public void message( String msg ) {
// ...
}
}
class TextSzal extends Thread { // Szál, ami írogat a
private LogIro lf; // log file-ba
TextSzal( LogIro lf, String ID) {
super(ID); this.lf = lf;
}
public void run() {
while (true) {
lf.message( getName() ); // Kiírja a nevét és
lf.message( " fut\n" ); // az állapotát
}
}
}
public class Versenges1 {
public static void main(String args[]) {
LogIro log = new LogIro(); // Log file def.
TextSzal t1 = new TextSzal( log, "1. szál" ),
t2 = new TextSzal( log, "2. szál" );
t1.start();
t2.start();
}
}
A teljes forrás: Versenges1.java
|
// Race Condition alap probléma
import java.io.*;
class LogIro { // A kritikus rész
private FileWriter logfile;
public synchronized void message( String msg ) { // Szinkronizáció
// ...
}
}
class TextSzal extends Thread { // Szál, ami írogat a
private LogIro lf; // log file-ba
TextSzal( LogIro lf, String ID) {
super(ID); this.lf = lf;
}
public void run() {
while (true) {
lf.message( getName() ); // Kiírja a nevét és
lf.message( " fut\n" ); // az állapotát
}
}
}
public class Versenges2 {
public static void main(String args[]) {
LogIro log = new LogIro(); // Log file def.
TextSzal t1 = new TextSzal( log, "1. szál" ),
t2 = new TextSzal( log, "2. szál" );
t1.start();
t2.start();
}
}
A teljes forrás: Versenges2.java
|
// Egyszerű számláló példa rendes sorrenddel
public class SimpleCount2 extends Thread {
static int n = 1; // Osztály szintű számláló
static Object kritikus_resz = new Object();// Egy objektum segítségével
public void run() {
for (int i=1; i<=4; i++) {
synchronized (kritikus_resz) { // szinkronizálunk
System.out.print(n + " "); // kiírjuk, majd
n++; // növeljük
} // Szinkronizációs blokk vége
}
}
public static void main(String args[]) {
Thread thr1 = new SimpleCount2(), // Két szálat létrehozunk,
thr2 = new SimpleCount2();
thr1.start(); // majd elindítunk
thr2.start();
}
}
A teljes forrás: SimpleCount2.java
|
// Író/olvasó probléma synchrnonized megoldással
import java.util.Random;
import java.util.Vector;
class Dolgozo extends Thread {
static volatile int m_reading = 0;
static public volatile Vector tomb = new Vector(10);
int ID;
boolean running = true;
Integer m_readLock = new Integer(0);
Random rnd = new Random();
Dolgozo(int ID) { super(); this.ID = ID; }
public void stopp() { running = false; }
public void run() {
int dummy;
System.out.println("indulok");
while (running) {
write((int) (100.0 * rnd.nextDouble()));
for(int i=0; i<1+(int) 10.0 * rnd.nextDouble(); i++) {
dummy = read();
try { sleep(java.lang.Math.abs(rnd.nextLong()) % 490 + 10); }
catch (InterruptedException e) {}
}
}
}
public int read() {
Integer readData;
synchronized( m_readLock ) {
m_reading++;
} // unlock readers
// do read (may take significant time...)
readData = (Integer) tomb.get(ID);
System.out.println( "Read: " + ID + "-->" + readData);
synchronized( m_readLock ) {
m_reading--;
}// unlock readers
return readData.intValue();
}
public void write( int x ) {
boolean succeeded = false;
while( !succeeded ) {
synchronized( m_readLock ) {
if( m_reading == 0 ) {
// do write (may take significant time...)
System.out.println( "Write:" + ID + "-->" + x);
tomb.insertElementAt( new Integer(x), ID);
succeeded = true;
}
}
if( succeeded == false )
Thread.currentThread().yield();
}
}
}
public class RW_1 {
static public void main(String args[]) {
Dolgozo[] d = new Dolgozo[10];
for (int i=0; i<10; i++) {
Dolgozo.tomb.add(new Integer(0));
d[i] = new Dolgozo(i);
}
for (int i=0; i<10; i++)
d[i].start();
}
}
A teljes forrás: RW_1.java
|
import java.util.*;
class ElemType { // általánosan elem típus
// ...
}
class Monitor { // szinkronizált rutinok a monitorban
ElemType row[]; // lista
int first=0,last=0, num_of_elements=0, row_length;
public Monitor(int row_length) {
row = new ElemType[this.row_length = row_length];
}
public synchronized void putMaterial( Thread th, ElemType e ) {
while ( num_of_elements == row_length ) {
System.out.println(th.getName() + " várakozik");
try { wait(); } catch (InterruptedException ex) {}
}
row[last] = e;
last = (last + 1) % row_length;
num_of_elements++;
notify();
}
public synchronized ElemType getMaterial( Thread th ) {
ElemType e;
while ( num_of_elements == 0 ) {
System.out.println(th.getName() + " várakozik");
try { wait(); } catch (InterruptedException ex) {}
}
e = row[first];
first = (first + 1) % row_length;
num_of_elements--;
notify();
return e;
}
}
class Producer extends Thread { // termelő
Monitor monitor;
ElemType e;
int made_elements = 0, max_elements;
Random rnd = new Random();
public Producer(String name, Monitor monitor, int max_elements) {
super(name);
this.monitor = monitor;
this.max_elements = max_elements;
e=ElemType.newValue(); // első elem generálása
}
public void run() { // termelés
while ( e.value() != ElemType.NULL_ELEMENT ) { // amíg nincs null elem
try {sleep(Math.abs(rnd.nextInt()) % 1000);}
catch (InterruptedException ex) {}
monitor.putMaterial( this, e );
System.out.println( getName() + ":\t" + e.toString() );
if (made_elements < max_elements) {
e=ElemType.newValue();
made_elements++;
}
else e=ElemType.makeNull();
}
monitor.putMaterial(this, e); //NULL_ELEMNT jelzi a véget
}
}
class Consumer extends Thread { // fogyasztó
Monitor monitor;
ElemType e;
Random rnd = new Random();
public Consumer(String name, Monitor monitor) {
super(name);
this.monitor = monitor;
}
public void run() { // fogyasztás, amíg van értelmes elem
while (true) {
try {sleep(Math.abs(rnd.nextInt()) % 1000);}
catch (InterruptedException ex) {}
e = monitor.getMaterial( this );
if (e.value() == ElemType.NULL_ELEMENT) break;
System.out.print( getName() );
e.showValue();
}
}
}
public class WaitNotify {
public static void main(String s[]) {
Monitor monitor = new Monitor(5);
Producer producer = new Producer("Termelő", monitor, 15);
Consumer consumer = new Consumer("Fogyasztó", monitor);
producer.start(); consumer.start();
}
}
A teljes forrás: WaitNotify.java
|