方法一 通过访问共享变量的方式(注:需要处理同步问题) 
方法二 通过管道流

其中方法一有两种实现方法,即 
方法一a)通过内部类实现线程的共享变量 

public class Innersharethread {     
    public static void main(String[] args) {     
        Mythread mythread = new Mythread();     
        mythread.getThread().start();     
        mythread.getThread().start();     
        mythread.getThread().start();     
        mythread.getThread().start();     
    }     
}     
class Mythread {     
    int index = 0;     
     
    private class InnerThread extends Thread {     
        public synchronized void run() {     
            while (true) {     
                System.out.println(Thread.currentThread().getName()     
                        + "is running and index is " + index++);     
            }     
        }     
    }     
     
    public Thread getThread() {     
        return new InnerThread();     
    }     
}    
   
/** 
 * 通过内部类实现线程的共享变量 
 * 
 */ 
public class Innersharethread {  
    public static void main(String[] args) {  
        Mythread mythread = new Mythread();  
        mythread.getThread().start();  
        mythread.getThread().start();  
        mythread.getThread().start();  
        mythread.getThread().start();  
    }  
}  
class Mythread {  
    int index = 0;  
   
    private class InnerThread extends Thread {  
        public synchronized void run() {  
            while (true) {  
                System.out.println(Thread.currentThread().getName()  
                        + "is running and index is " + index++);  
            }  
        }  
    }  
   
    public Thread getThread() {  
        return new InnerThread();  
    }  
}
View Code

相关文章:

  • 2021-12-15
  • 2021-07-12
  • 2021-11-13
  • 2022-01-11
  • 2021-12-12
  • 2021-08-03
  • 2021-08-07
  • 2022-12-23
猜你喜欢
  • 2021-09-20
  • 2021-08-11
  • 2022-03-08
  • 2021-12-10
  • 2021-12-14
  • 2021-10-19
相关资源
相似解决方案