יום שלישי, 16 בינואר 2018

תכנות מקבילי Java Thread


Thread


בג'אווה כמו בהרבה שפות תכנות, צריך לפעמים שהמעבד יעשה מספר דברים במקביל. לשם כך נועדו ה-Threads.


הורדת מאמר (PDF): כאן או כאן.
ראו גם: Java מההתחלה, מדריך ביוטיוב של life michael.








לנוחיותכם, הנה הקוד שמופיע במדריך ה-PDF (עם שינויים קטנים):

המחלקה Test:
package test;

public class Test {

    public static String getMarketName() {
// System.out.print("[within getMarketName " 
// +Thread.currentThread().getName()+"] "); 
        return "Carnel";
    }

    public static void main(String[] args) {
        Yarkan yarkan1 = new Yarkan("Moshe", "Banana");
        Yarkan yarkan2 = new Yarkan("Haim ", "Orange");
        Thread t1 = new Thread(yarkan1);
        Thread t2 = new Thread(yarkan2);
        
        t1.start();
        t2.start();
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " "
                    + Test.getMarketName() + " ");
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        try {
//            Thread.sleep(100);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println("Here!!");
        
    }
}



המחלקה Yarkan:

package test;
public class Yarkan implements Runnable
{
    private int iInstance;
    private static int iStatic;
    private String name;
    private String product;
    public Yarkan(String name, String product)
    {
        super();
        this.name = name;
        this.product = product;
    }
    
    public void run() 
    {
        for (int iLocal = 0; iLocal < 10; iLocal++)
        {
            iInstance++;
            iStatic++;
            System.out.print(Thread.currentThread().getName() + " "
                    + name + " sells " + product + " iLocal=" + iLocal
                    + " iInstance=" + iInstance + " iStatic=" + iStatic);
            System.out.println();
            
            try
            {
                Thread.sleep(10);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    public String getName()
    {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }

    public String getProduct() {
        return product;
    }

    public void setProduct(String product) {
        this.product = product;
    }

}















הנושא הזה חשוב להבנה של פעולות גרפיות ב-Swing.
לדוגמה:
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });

    //
    //
    //
   }
ראו בנושא: Initial Threads.





2 תגובות: