תוכנית הדגמה קצת יותר עצמאית
-בואו נשנה את אחת מתוכניות ההדגמה הקודמות באופן שתגרום ל threads לעשות פעולה קצת
יותר עצמאית/ממשית כך שתוכל למעשה לראות הוכחה כל שהיא לפעולה בו-זמנית.
/*File Thread03.java Copyright 1997, R.G.Baldwin Illustrates instantiation and running of threads using the runnable interface. Each of two threads counts from zero to four and displays the count, sleeping a random amount of time between counts.
Tested using JDK 1.1.3 under Win95.
The output is: Thread[thrdA,5,main] cnt is 0 Thread[threadB,5,main] cnt is 0 Thread[threadB,5,main] cnt is 1 Thread[threadB,5,main] cnt is 2 Thread[thrdA,5,main] cnt is 1 Thread[thrdA,5,main] cnt is 2 Thread[threadB,5,main] cnt is 3 Thread[thrdA,5,main] cnt is 3 Thread[threadB,5,main] cnt is 4 Thread[thrdA,5,main] cnt is 4 **********************************************************/
class Thread03 { static public void main(String[] args){ //Instantiate two new thread objects with names of // different lengths which helps when viewing the // output. Thread threadA = new Thread(new MyThread(),"thrdA"); Thread threadB = new Thread(new MyThread(),"threadB"); //Start them running threadA.start(); threadB.start(); try{//delay for one second Thread.currentThread().sleep(1000); }catch(InterruptedException e){} }//end main} //end class Thread03 //=======================================================// class MyThread implements Runnable{ public void run(){ for(int cnt = 0; cnt < 5; cnt++){ System.out.println(Thread.currentThread() + " cnt is " + cnt); try{//delay a random amount of time Thread.currentThread().sleep( (int)(Math.random() * 100)); }catch(InterruptedException e){} }//end for-loop }//end run }//end class MyThread |
תוכנית זו עושה מופעים לשני אובייקטים עצמאיים של threads ומתחילה להריץ אותם באופן לא מסונכרן ((asynchronously . כל thread סופר מאחד עד ארבע ומציג את הספירה יחד עם השם שלו . כל thread גם 'ישן' במשך פרק זמן שרירותי בין הספירות.
בגלל השימוש בזמן שינה רנדומלי תהיה תוצאה שונה לכל הרצה. התוצאה של אחת ההרצות מוצגת בהערות בתחילת התוכנית. אתה יכול לראות איך כל thread:
- מפעיל (activates)
- סופר
- מציג
- ישן
כשהוא בלתי תלוי בפעולות של ה thread השני. (מלבד העובדה שהם חייבים לחלוק במשאבים זמינים כששניהם ערים). הפלט של thread אחד ממוזג עם של השני. זה קורה כי שני ה threads רצים בו-זמנית ובאופן בלתי מסונכרן. שתי מתודות ה run() :
- רצות באותו הזמן
- מתחרות על המשאבים אם הן לא ישנות
- מציגות את הפלט שלהן בכל פעם שיש להן מה להציג והן יכולות להשיג שליטה על תזרים הפלט הסטנדרטי.
לתוכנת ג'אווה יכולים להיות threads רבים, והם יכולים לרוץ בו זמנית, בין באופן מסונכרן ובין באופן לא מסונכרן.
תכונות ה threads
כפי שהוסבר קודם, ה threads של ג'אווה הם אובייקטים של המחלקהThread שהיא חלק מחבילת java.lang .
המחלקהThread מיישמת הגדרה של java threads שהיא בלתי תלויה בפלטפורמה. על כל פנים, היישום בפועל של פעולה בו זמנית, מסופק על ידי יישום של מערכת ספציפית שנבנה בתוך המכונה הווירטואלית של ג'אווה (the Java Virtual Machine) לפלטפורמה מסוימת.
למטרות שלנו, היישום היסודי איננו חשוב. אנו נתעלם ממנו ונתכנת ברמת ה API thread.
היכן מתבצעת הפעולה, המתודה run()
כאשר אתה מיישם תוכנית שהיא threaded, אתה דורס את המתודה run() של המחלקה Thread ובונה את הפונקציונליות של התוכנית שהיא threaded במתודת ה run().
ברור שהמתודה run() יכולה להפעיל מתודות אחרות. תריץ את ה-thread על ידי הפעלת המתודה start() על אובייקט ה Thread שלך.
המתודה start() מפעילה את המתודה run() (וכמו כן מטפלת ברקע גם במספר tasks הכרחיים אחרים). שים לב שאף אחת מהמתודות האלה לא לוקחת פרמטרים כל שהם.
אינך מוגבל לשימוש חד פעמי במתודה run() בתוכנית שהיא threaded. באפשרותך להגדיר מגוון של מחלקות בתוכנית שלך שיורשות מThread או לחלופין מיישמות את Runnable ( הממשק הניתן להרצה). יש לך אפשרות ליצור מופעים של אובייקטים רבים שלThread מכל אחת מהמחלקות האלה.
לכל אחת מהמחלקות האלה יש מתודה run() דרוסה משלה שהיא בלתי תלויה במתודות הrun() של המחלקות האחרות. התוכנית הבאה שידרגה קלות אחת מהתוכניות הקודמות על ידי הגדרה של שתי מחלקות חדשות שמהן יוצרים מופעים לאובייקטים שהם threaded. לכל מחלקה יש מתודת run() משלה שהיא שונה ממתודת run() במחלקה אחרת. (למרות שהן עושות דברים דומים כדי שיהיה קל יותר לראות את התוצאות).
לשני אובייקטים של Thread של כל אחת מהמחלקות יוצרים מופעים ומריצים אותם. בדומה למקרה קודם, הם רצים באופן בלתי מסונכרן יחסית אחד לשני והפלט שהם מוציאים ממוזג על המסך.
/*File Thread04.java Copyright 1997, R.G.Baldwin Illustrates instantiation and running of threads using the runnable interface where two different classes are defined each of which uses the Runnable interface. The run() method in one class is different from the run() method in the other class.
Two Thread objects are instantiated and started for each of the two thread classes.
Each of the threads counts from zero to four and displays the count, sleeping a random amount of time between counts. The format of the display is different between the two thread classes.
Tested using JDK 1.1.3 under Win95. The output is for one particular run was:
Thread[thrdA,5,main] cnt is 0 Thread[threadB,5,main] cnt is 0 The actual cnt is 0 Thread[Xthrd,5,main] The actual cnt is 0 Thread[Ythread,5,main] Thread[thrdA,5,main] cnt is 1 Thread[threadB,5,main] cnt is 1 Thread[thrdA,5,main] cnt is 2 The actual cnt is 1 Thread[Ythread,5,main] The actual cnt is 1 Thread[Xthrd,5,main] Thread[threadB,5,main] cnt is 2 The actual cnt is 2 Thread[Ythread,5,main] Thread[thrdA,5,main] cnt is 3 The actual cnt is 3 Thread[Ythread,5,main] Thread[thrdA,5,main] cnt is 4 The actual cnt is 2 Thread[Xthrd,5,main] The actual cnt is 4 Thread[Ythread,5,main] Thread[threadB,5,main] cnt is 3 The actual cnt is 3 Thread[Xthrd,5,main] The actual cnt is 4 Thread[Xthrd,5,main] Thread[threadB,5,main] cnt is 4 **********************************************************/
class Thread04{ static public void main(String[] args){ //Instantiate two new thread objects of one type Thread threadA = new Thread( new OneThreadClass(),"thrdA"); Thread threadB = new Thread( new OneThreadClass(),"threadB"); //Instantiate two new thread objects on another type Thread Xthread = new Thread( new AnotherThreadClass(),"Xthrd"); Thread Ythread = new Thread( new AnotherThreadClass(),"Ythread"); //Start them running threadA.start(); threadB.start(); Xthread.start(); Ythread.start(); try{//delay for one second Thread.currentThread().sleep(1000); }catch(InterruptedException e){} }//end main}//end class Thread04 //=======================================================//
class OneThreadClass implements Runnable{ public void run(){ for(int cnt = 0; cnt < 5; cnt++){ System.out.println(Thread.currentThread() + " cnt is " + cnt); try{//delay a random amount of time Thread.currentThread().sleep( (int)(Math.random() * 100)); }catch(InterruptedException e){} }//end for-loop }//end run }//end class OneThreadClass //=======================================================// class AnotherThreadClass implements Runnable{ public void run(){ for(int cnt = 0; cnt < 5; cnt++){ System.out.println("The actual cnt is " + cnt + " " + Thread.currentThread()); try{//delay a random amount of time Thread.currentThread().sleep( (int)(Math.random() * 100)); }catch(InterruptedException e){} }//end for-loop }//end run }//end class AnotherThreadClass |