The difference between ordinary class and thread class

 

 

Suppose a class is SubThread, and its init() method implements an anonymous inner class, and the other is Outer, which is responsible for printing incoming strings.

 

An example is as follows:

 

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();
		
	}
	
	
}

 

 

The Outer class is as follows:

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();
		}
	}
	
}

 

 

 

We can simply understand the relationship between thread classes and ordinary classes:

The ordinary class is like the landlord's house, and there is a function in the house to go to the toilet.

Thread classes are like moving workers.

 

The actual business logic should be placed in the ordinary class, and there should be no logic in the thread class, just refer to the ordinary class directly, and then start() method.

 

Suppose the worker wants to enter the room to go to the toilet and lock the toilet. This function is also a self-class in the common class and has nothing to do with the thread class.

 

 

 my new blog

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326674605&siteId=291194637