2015-09-15 18 views
-1

我是新來的線程,我想知道如何定義兩個或多個不同的線程在Java程序中做什麼。我是否在同一個公共無效運行方法中定義它們?如果是這樣,我該怎麼做?我想威脅T1調用增量法,T2調用減量方法和他們兩個來調用值方法在java中定義兩個不同的線程

下面的代碼示例:

package interference; 

/** 
* 
* @author rodrigopeniche 
*/ 
public class Interference implements Runnable{ 

/** 
* @param args the command line arguments 
* 

*/ 

Counter counter1= new Counter(); 

class Counter{ 

    private int c= 0; 

    public void increment() 
    { 
     c++; 
    } 

    public void decrement() 
    { 
     c--; 
    } 

    public int value() 
    { 
     return c; 
    } 

} 

public static void main(String[] args) { 
    // TODO code application logic here 


Thread t1= new Thread(new Interference()); 
Thread t2= new Thread(new Interference()); 
t1.start(); 
t2.start(); 

} 



@Override 
public void run() { 

counter1.increment(); 
counter1.decrement(); 
counter1.value(); 



} 

} 
+0

順便說一句,我知道這會造成干擾。這是一個用於學習目的的示例 –

+0

是您想實現的生產者消費類型問題嗎? – virendrao

+0

_how我可以在Java程序中定義兩個或多個不同的線程嗎?_一個線程的run()方法定義了它的功能。 –

回答

1

您可以設置名稱類似的線程thread1, thread2。之後,在run方法中,檢查當前正在運行的線程的名稱並執行必要的操作。

如果您需要運行更長時間,則必須在運行方法內添加while循環。

public static void main(String[] args) { 

    Interference interference = new Interference();//create a new Interference object 

    Thread t1 = new Thread(interference, "thread1");//pass the runnable interference object and set the thread name 
    Thread t2 = new Thread(interference, "thread2");//pass the runnable interference object and set the thread name 
    t1.start(); 
    t2.start(); 
} 

@Override 
public void run() { 

    while (true) {//to run it forever to make the difference more visual 

     String threadName = Thread.currentThread().getName();//get the current thread's name 
     if (threadName.equals("thread1")) {//if current thread is thread1, increment 
      counter1.increment(); 
     } else if (threadName.equals("thread2")) {//if current thread is thread2, decrement 
      counter1.decrement(); 
     } 

     System.out.println(counter1.value());//print the value 
    } 
} 

當你運行代碼時,你可以看到count是以隨機的方式上下移動的。

-1

在您當前的代碼中,counter1Interference類的實例變量。您創建Interference的兩個實例,然後使用它們創建兩個Thread對象。線程開始運行時,每個Thread實際上都在處理它自己的counter1副本。我想這可能不是你所期望的。

package interference; 

public class Interference { 
    static class Counter { 
     private int c = 0; 

     public void increment() { 
      c++; 
     } 

     public void decrement() { 
      c--; 
     } 

     public int value() { 
      return c; 
     } 
    } 

    public static void main(String[] args) { 
     Counter counter = new Counter(); 

     Thread t1 = new Thread(new Runnable() { 
      public void run() { 
       counter.increment(); 
       System.out.println(counter.value()); 
      } 
     }); 
     Thread t2 = new Thread(new Runnable() { 
      public void run() { 
       counter.decrement(); 
       System.out.println(counter.value()); 
      } 
     }); 
     t1.start(); 
     t2.start(); 
    } 
} 
相關問題