假设一个类是SubThread,它的init()方法实现了一个匿名内部类,另一个是Outer,这个类专门负责打印传入的字符串。
举例如下:
package germmy.home.testmultithread; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockTest { Outer outer=new Outer(); public static void main(String[] args) { new LockTest().init(); } void init(){ new Thread(new Runnable() { public void run() { while(true){ outer.output("zhangsanshigehaoren"); } } }).start(); new Thread(new Runnable() { public void run() { while(true){ outer.output("taiwanxiangtaidu"); } } }).start(); } }
Outer类如下:
class Outer{ Lock lock=new ReentrantLock(); void output(String name){ lock.lock(); try { for(int i=0;i<name.length();i++){ System.out.print(name.charAt(i)); } System.out.println(); } finally{ lock.unlock(); } } }
扫描二维码关注公众号,回复:
286657 查看本文章
我们可以简单的理解线程类和普通类之间的关系:
普通类好比是房东的房子,房子里面有个功能是上厕所。
线程类好比是搬家的工人。
实际的业务逻辑应该是放在普通类中的,线程类中应该没有什么逻辑,直接引用普通类,然后start()方法即可。
假设工人要进房间上厕所,给厕所上锁,这个功能也是普通类中自类的,和线程类没有关系。