读写锁、线程池、定时器

扩展知识1:读写锁
ReadWriteLock接口:可以实现多个读线程同时读取数据,写线程需要互斥执行。
读|写 、写|写 需要互斥
读|读 不需要互斥

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteDemo {

private int number=0;
private ReadWriteLock lock=new ReentrantReadWriteLock();

public void read() {
	lock.readLock().lock();
	try {
		System.out.println(Thread.currentThread().getName()+"读取了:"+number);
	} finally {
		lock.readLock().unlock();
	}
}

public void write(int number) {
	lock.writeLock().lock();
	try {
		System.out.println(Thread.currentThread().getName()+"写入了"+number);
		this.number=number;
		
	} finally {
		lock.writeLock().unlock();
	}
}

}

测试类:
import java.util.Random;

public class Test {
public static void main(String[] args) {
ReadWriteDemo rw=new ReadWriteDemo();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rw.write(new Random().nextInt(100));
}
}).start();

	Runnable r=new Runnable() {
		@Override
		public void run() {
			rw.read();		
		}
	};
	for(int i=0;i<100;i++) {
		new Thread(r).start();
	}
}

}

扩展知识2:线程池
为什么需要线程池:
例如有非常的多的任务需要多线程来完成,且每个线程执行时间不会太长,这样会频繁的创建和销毁线程。频繁创建和销毁线程会比较耗性能。如果有了线程池就不要创建更多的线程来完成任务,因为线程可以重用。
线程池用维护者一个队列,队列中保存着处于等待(空闲)状态的线程。不用每次都创建新的线程。
和线程池相关的接口和类存在java.util.concurrent并发包中。
接口:
1 Executor:线程池的核心接口,负责线程的创建使用和调度的根接口
2 ExecutorService: Executor的子接口,线程池的主要接口, 提供基本功能。
3 ScheduledExecutorService: ExecutorService的子接口,负责线程调度的子接口。
实现类:
1 ThreadPoolExecutor:ExecutorService的实现类,负责线程池的创建使用。
2 ScheduledThreadPoolExecutor:继承 ThreadPoolExecutor,并实现 ScheduledExecutorService接口,既有线程池的功能,又具有线程调度功能。
3 Executors:线程池的工具类,负责线程池的创建。
newFixedThreadPool();创建固定大小的线程池。
newCachedThreadPool();创建缓存线程池,线程池大小没有限制。根据需求自动调整线程数量。
newSingleThreadExecutor();创建单个线程的线程池,只有一个线程。
newScheduledThreadPool();创建固定大小的线程池,可以延迟或定时执行任务。

案例一:使用线程池实现卖票

public class Ticket implements Runnable{
private int ticket=100;

@Override
public void run() {
	while(true) {
		if(ticket<=0) {
			break;
		}
		System.out.println(Thread.currentThread().getName()+"卖第"+ticket+"张票");
		ticket--;
	}
}

}

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
public static void main(String[] args) {
Ticket ticket=new Ticket();
ExecutorService threadPool = Executors.newFixedThreadPool(4);
for(int i=0;i<4;i++) {
threadPool.submit(ticket);
}
threadPool.shutdown();
System.out.println(“主线程执行完毕…”);

}

}

案例二:线程池计算1-100的和,要求采用Callable接口
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test {
public static void main(String[] args) throws Exception {
ExecutorService threadPool = Executors.newFixedThreadPool(4);
List<Future> list=new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future future = threadPool.submit(new Callable() {

			@Override
			public Integer call() throws Exception {
				int sum = 0;
				for (int i = 0; i <= 100; i++) {
					Thread.sleep(10);
					sum += i;
				}
				System.out.println(Thread.currentThread().getName() + "计算完毕");
				return sum;
			}
		});
		list.add(future);
	}

	threadPool.shutdown();
	System.out.println("主线程结束了。。。。");
	for (Future<Integer> fu : list) {
		int s = fu.get();
		System.out.println(s);
	}
	

}

}

案例三:延迟执行任务
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Test2 {
public static void main(String[] args) throws Exception{
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
List<Future> list=new ArrayList<>();
for(int i=0;i<10;i++) {
Future future=threadPool.schedule(new Callable() {

			@Override
			public Integer call() throws Exception {
				int ran=new Random().nextInt(100);
				System.out.println(Thread.currentThread().getName()+"...."+ran);
				return ran;
			}
		},3,TimeUnit.SECONDS);
		list.add(future);
	}
	threadPool.shutdown();
	System.out.println("主线程结束了...........");
	for (Future<Integer> future2 : list) {
		int n=future2.get();
		System.out.println(n);
	}
	
}

}

扩展知识3:定时器Timer
public class TimerDemo {
public static void main(String[] args){
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
System.out.println("*******************");
}
};
timer.schedule(timerTask,1000 ,1000);
}
}

总结
1 多线程访问临界资源
数据安全问题?
2 解决安全问题
同步 + 锁
3 同步代码块
synchronized(metux){

}
锁:引用类型 ,唯一的

4 同步方法
方法的返回值前面 synchronized
非静态方法 锁:this
静态方法 锁:类名.class

5 可重入锁 ReentrantLock
Lock lock=new ReeentrantLock();
lock.lock()
try{

}finally{
  lock.unlock();
}

6 死锁
1多个锁 ,多个线程
2同步中嵌套同步
7 单例模式优化
懒汉式写法
8 线程通信
Object中三个方法
wait(); 等待
notifiy(); 唤醒
notifyAll();唤醒所有的

jdk1.5 Lock通信
Conditon代替监视器方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值