Java 线程池总结

something

  • volatile
  • synchronized

1. implements Runnable

/**调用*/
TestRunnable tt= new TestRunnable ();//create TestThread class
Thread t= new Thread(tt);// create a Thread class
t.start(); //enable Runnable states
		
class TestRunnable implements Runnable{
	@Override
	public void run(){
		System.out.println(Thread.currentThread().getName() +" is running");
	}
}

2. extends Thread

/**调用*/
new TestThread().start();

class TestThread extends Thread {
	@Override
	public void run() {
		System.out.println(" TestThread1 is running");
	}
} 

3. ThreadGroup 线程组

类似 数组

  • 创建线程组
// 创建线程组
ThreadGroup threadGroup = new ThreadGroup("Searcher");
Result result=new Result();

TestRunnable testRunnable =new TestRunnable ();
// 创建一个任务,10个线程完成
for (int i=0; i<10; i++) {
	Thread thread=new Thread(threadGroup, testRunnable );
	thread.start();
}
  • ThreadGroup 一些操作
// 查看线程组消息
System.out.printf("active 线程数量: %d\n",threadGroup.activeCount());
System.out.printf("线程组信息明细\n");
threadGroup.list();
System.out.println("========华丽丽1=======");

// 遍历线程组
Thread[] threads=new Thread[threadGroup.activeCount()];
threadGroup.enumerate(threads);
for (int i=0; i<threadGroup.activeCount(); i++) {
	System.out.printf("Thread %s: %s\n",threads[i].getName(),threads[i].getState());
}
System.out.println("========华丽丽2=======");

// 当前线程名称
String name=Thread.currentThread().getName();

4. Callable<?>

  • 特点:有返回值

  • 调用

// todo 

线程类


public class SumTask implements Callable<Integer> {
	//定义每个线程计算的区间
	private int startNumber;
	private int endNumber;
	
	public SumTask(int startNumber, int endNumber){
		this.startNumber=startNumber;
		this.endNumber=endNumber;
	}
	
	@Override
	public Integer call() throws Exception {
		int sum = 0;
		for(int i=startNumber; i<=endNumber; i++) {
			sum = sum + i;
		}
		Thread.sleep(new Random().nextInt(1000));
		
		System.out.printf("%s: %d\n",Thread.currentThread().getName(),sum);
		return sum;
	}
}

* 三种线程类型

5. Executor (JDK 5)

6. Fork-Join (JDK 7)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值