重点:单例模式,阻塞队列,定时器,线程池
/**
* User:yang
*/
public class ThreadDemo16 {
//饿汉模式
//实例创建出现在类加载阶段
static class Singleton {
//希望是单例类,只有一个实例
//县创建一个成员,保存唯一的实例
private static Singleton instanse = new Singleton();
//在提供方法获取实例
public static Singleton getInstance() {
return instanse;
}
//把构造方法私有,防止其他代码创建实例
private Singleton() {
}
}
public static void main(String[] args) {
//如何获取这个实力
Singleton singleton=Singleton.getInstance();
}
}
/**
* User:yang
*/
public class ThreadDemo17 {
//懒汉模式
//创建实例是在第一次使用getinstance的时候,比饿汉模式迟
static class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
private Singleton() {
}
}
public static void main(String[] args) {
Singleton singleton=Singleton.getInstance();
}
}
/**
* User:yang
*/
public class ThreadDemo18 {
//线程安全版本懒汉模式
//创建实例是在第一次使用getinstance的时候,比饿汉模式迟
static class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
synchronized (Singleton.class){
if (instance == null) {
instance = new Singleton();
}
}
return instance;
}
private Singleton() {
}
}
public static void main(String[] args) {
Singleton singleton=Singleton.getInstance();
}
}
/**
* User:yang
*/
public class ThreadDemo18 {
//线程安全版本懒汉模式
//创建实例是在第一次使用getinstance的时候,比饿汉模式迟
static class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
private Singleton() {
}
}
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* User:yang
*/
public class ThreadDemo20 {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
//创建生产者线程
Thread producer = new Thread() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
try {
System.out.println("producer生产 str" + i);
queue.put("str" + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
producer.start();
//消费者线程
Thread customer = new Thread() {
@Override
public void run() {
while (true) {
try {
String elem = queue.take();
Thread.sleep(1000);
System.out.println("customer获取到" + elem);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
customer.start();
try {
producer.join();
customer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* User:yang
*/
public class ThreadDemo21 {
//先基于数组的方式实现一个普通队列
//再改进程阻塞队列
static class BlockingQueue {
private int[] items = new int[1000];
//约定[head,tail)是一个前闭后开区间
//初始状态head,tail为0,表示区间为空
//从head取元素
private int head = 0;
//往tail添加元素
private int tail = 0;
//表示元素个数
public int size = 0;
//引入一个“锁对象”
private Object locker = new Object();
//入队列
public void put(int value) throws InterruptedException {
synchronized (locker) {
while (size == items.length) {//wait结束之后,不一定队列不是满的
//队列已经满了,阻塞等待
locker.wait();
}
//队列没有满,插入到tail位置
items[tail] = value;
tail++;
//处理tail超出边界
if (tail >= items.length) {
tail = 0;
}
size++;
locker.notifyAll();
}
}
public Integer take() throws InterruptedException {
int ret = 0;
synchronized (locker) {
//队列为空,阻塞等待
while (size == 0) {
locker.wait();
}
ret = items[head];
head++;
if (head >= items.length) {
head = 0;
}
size--;
locker.notifyAll();
}
return ret;
}
}
public static void main(String[] args) throws InterruptedException {
BlockingQueue queue = new BlockingQueue();
Thread producer = new Thread() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
try {
System.out.println("产生了元素" + i);
queue.put(i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
producer.start();
Thread customer = new Thread() {
@Override
public void run() {
while (true){
int ret= 0;
try {
ret = queue.take();
System.out.println("消费了元素"+ret);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
customer.start();
producer.join();
customer.join();
}
public static void main1(String[] args) throws InterruptedException {
BlockingQueue queue = new BlockingQueue();
queue.put(1);
queue.put(2);
queue.put(3);
queue.put(4);
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
}
}
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;
/**
* User:yang
* 一个简单定时器
*/
public class ThreadDemo22 {
//每个Task就表示一个具体的任务实例
//task放入优先队列的时候要比较优先级
static class Task implements Comparable<Task> {
//啥时候执行
private long time;
//执行啥
private Runnable command;
//
public Task(Runnable command, long time) {
this.command = command;
//绝对时间
this.time = System.currentTimeMillis() + time;
}
public void run() {
command.run();
}
@Override
public int compareTo(Task o) {
//时间小的排前面
return (int) (this.time - o.time);
}
}
static class Timer {
//创建一个带优先级的阻塞队列
private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
// 用这个对象来完成线程之间的协调任务
private Object mailbox = new Object();
//schedule方法就是把一个task放到Timer中
public void schedule(Runnable command, long after) {
Task task = new Task(command, after);
queue.put(task);
synchronized (mailbox) {
mailbox.notify();
}
}
public Timer() {
Thread worker = new Thread() {
@Override
public void run() {
while (true) {
//去队首元素,看能不能执行
try {
Task task = queue.take();
long currentTime = System.currentTimeMillis();
if (currentTime >= task.time) {
//执行任务
task.run();
} else {
//时间没到继续等
queue.put(task);
synchronized (mailbox) {
mailbox.wait(task.time - currentTime);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
worker.start();
}
}
public static void main(String[] args) {
Timer timer=new Timer();
Runnable comand=new Runnable() {
@Override
public void run() {
System.out.println("时间到了");
timer.schedule(this,3000);
}
};
System.out.println("安排任务");
timer.schedule(comand,3000);
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* User:yang
*/
public class ThreadDemo23 {
public static void main(String[] args) {
//创建包含10个线程的线程池
ExecutorService pool= Executors.newFixedThreadPool(10);
// //创建线程数量动态变化的的线程池
// ExecutorService pool2=Executors.newCachedThreadPool();
int i = 0;
for (; i <100 ; i++) {
int finalI = i;
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("hello"+ finalI);
}
});
}
}
}
import javafx.concurrent.Worker;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* User:yang
*/
public class ThreadDemo24 {
static class ThreadPool {
//描述一个任务(runnable)
//组织很多任务,使用阻塞队列来保存当前的所有任务
private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
//描述一个线程,用来进行工作
static class worker extends Thread {
private BlockingQueue<Runnable> queue=null;
public worker(BlockingQueue<Runnable> queue){
this.queue=queue;
}
@Override
public void run() {
while (true) {
try {
Runnable runnable =queue.take();
runnable.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//八线程组织起来
private List<worker> workers=new ArrayList<>();
private static final int maxcount=10;
//核心接口execute
public void execute(Runnable command) throws InterruptedException {
if (workers.size()<maxcount){
//当前池子没有足够的线程,创建新的线程
worker worker=new worker(queue);
worker.start();
workers.add(worker);
}
queue.put(command);
}
}
public static void main(String[] args) throws InterruptedException {
ThreadPool pool=new ThreadPool();
for (int i = 0; i < 10; i++) {
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
});
}
}
}