Java线程传参方式

第一类:主动向线程传参

public class ThreadTest extends Thread {
 
    public ThreadTest() {
	}
	/**
	 *  第一种通过构造方法来传递参数
	 */
	public ThreadTest(String parameter ) {
		this.parameter  = parameter ;
	}
	
	/**
	 * 第二种通过变量传参
	 */
    private String parameter ;
    
	public void setParameter(String parameter) {
		this.parameter  = parameter ; 
	} 
	
	@Override
	public void run() {
		System.out.println("hello " + parameter );
	}
 
	public static void main(String[] args) {
		Thread thread1 = new ThreadTest("world");
		Thread thread2= new ThreadTest();
		
		((ThreadTest) thread2).setParameter("beautiful girl");
		thread1.start();
		thread2.start();
	}
}

注:Thread 中有些许内置方法,例如setName(String name)、setPriority(int newPriority)等,所以在利用变量传参时,变量应避免取此类名称。

第二类 线程主动获取参数

import java.util.Random;
 
class Data{
	int value = 0;
}
 
class Work{
	public void process(Data data, Integer[] numbers) {
		for (int n : numbers) {
			data.value += n;
		}
	}
}
public class ThreadTest extends Thread {
	
	private Work work;
 
	public ThreadTest(Work work){ 
		this.work = work; 
	}
 
	public void run() {
		Random random = new Random();
		Data data = new Data();
		int n1 = random.nextInt(1000);
		int n2 = random.nextInt(2000);
		int n3 = random.nextInt(3000);
		Integer[] numbers = {n1,n2,n3};
		work.process(data, numbers); // 使用回调函数
		System.out.println(String.valueOf(n1) + "+" + String.valueOf(n2) + "+" + String.valueOf(n3) + "=" + data.value);
	}
 
	public static void main(String[] args) {
		Thread thread = new ThreadTest(new Work());
		thread.start();
		
	}
}

你可能感兴趣的:(Java-多线程,java)