2016-04-03 104 views
0

我刚刚开始学习Java中的多线程,并且仍在思考一些问题。首先,延伸Thread的类是否可以有其他与它关联的实例方法,以便在其执行过程中调用 - 如果是,它是否可以在执行期间更改线程的状态?其次,如果这个类被阻塞等待信号量,它的实例方法是否仍然可以被调用?就像这2个线程的东西运行:阻塞线程的调用方法

Thread1 t; 
public class Thread1 extends Thread { 
    private int num; 
    public run() { 
     sem.acquire(); // here it blocks waiting for another thread 
         //to call its setInt function and release it 
     System.out.println("num is " + num); 
    } 
    public void setInt(int i) { 
     num = i; 
    } 
} 

public class Thread2 extends Thread { 
    public run() { 
     t.setInt(5); 
     sem.release(); 
    } 
} 

回答

0

为了证明你在找什么,这里是一个代码示例至极我测试:

package test2; 

import java.util.concurrent.Semaphore; 

public class mainclass { 

    static Thread1 t; 

    static Semaphore sem; 

    static Semaphore sem_protect; 

    public synchronized static void main (String[] args) { 

     sem = new Semaphore(0); 

     sem_protect = new Semaphore(1); 

     t = new Thread1(); 

     Thread1 th1 = new Thread1(); 
     th1.start(); 

     Thread2 th2 = new Thread2(); 
     th2.start(); 

     try { 
      synchronized (th2){ 
      th2.wait(); 
      } 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     System.out.println("The end !"); 
     } 


    public static class Thread1 extends Thread { 

     private int num; 

     public void run() { 

      try { 
       sem.acquire(); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } // here it blocks waiting for another thread 
          //to call its setInt function and release it 
      try { 
       sem_protect.acquire(); 
       System.out.println("num is " + num); 
       sem_protect.release(); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


     } 

     public synchronized void setInt(int i) { 

      try { 
       sem_protect.acquire(); 
       this.num = i; 
       sem_protect.release(); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


      System.out.println("value of num is: "+num); 
     } 
    } 

    public static class Thread2 extends Thread { 
     public void run() { 
      t.setInt(5); 
      sem.release(); 
     } 
    } 

} 

下面是这段代码的执行结果:

value of num is: 5 
The end ! 
num is 0 

有了这个结果,你可以看到你仍然可以从Thread2中访问类thread1的方法。这意味着你访问类实例的方法,线程没有方法。 (这是你的第一个问题的答案)

第一个线程的状态不会被第二个改变,num对于第一个线程仍然是0,线程每个都有自己的上下文。

即使我们用另一个信号保护对num的访问,我们也没有为两个线程设置相同的值num

3

这里有一些混淆。

  1. 线程没有方法。类有方法。
  2. 类不阻塞。线程被阻塞。
  3. 您可以随时调用任何方法。该方法本身可能是同步的,这会延迟进入它,或者它可能在内部使用同步,同上或信号量,同上。