/**
* 用两阶段终止模式终止监控操作
*/
public class MonitorThread extends Thread {
//在监控线程中添加一个volatile类型的标志变量,用于标识是否需要终止线程的执行
private volatile boolean terminated = false;
public void run() {
while (!Thread.interrupted()&&!terminated) {
// 执行监控操作
System.out.println("监控线程正在执行监控操作...");
try {
Thread.sleep(5000);
// 卡死
} catch (InterruptedException e) {
// 检查中断状态
System.out.println("监控线程被中断,准备退出...");
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
// 执行清理操作
System.out.println("监控线程正在执行清理操作...");
releaseResources();
}
public void terminate() {
//设置标志变量为true,并等待一段时间
terminated = true;
try {
join(5000); // 等待5秒钟,期间监控线程会检查terminated的状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void releaseResources() {
// 释放资源和进行必要的清理工作
System.out.println("监控线程正在释放资源和进行必要的清理工作...");
}
public static void main(String[] args) throws InterruptedException {
MonitorThread thread = new MonitorThread();
//启动监控线程
thread.start();
//主线程休眠期间,监控线程在执行监控操作
Thread.sleep(10000);
//终止监控线程
//thread.terminate();
thread.interrupt();
Thread.sleep(100000);
}
/**
* 用两阶段终止模式终止监控操作
*/
public class MonitorThread2 extends Thread {
//在监控线程中添加一个volatile类型的标志变量,用于标识是否需要终止线程的执行
private volatile boolean terminated = false;
public void run() {
while (!Thread.interrupted()&&!terminated) {
// 执行监控操作
System.out.println("监控线程正在执行监控操作...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("监控线程被中断,准备退出...");
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
// 执行清理操作
System.out.println("监控线程正在执行清理操作...");
releaseResources();
}
public void terminate() {
//设置标志变量为true,并等待一段时间
terminated = true;
try {
join(5000); // 等待5秒钟,期间监控线程会检查terminated的状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void releaseResources() {
// 释放资源和进行必要的清理工作
System.out.println("监控线程正在释放资源和进行必要的清理工作...");
}
public static void main(String[] args) throws InterruptedException {
MonitorThread2 thread = new MonitorThread2();
//启动监控线程
thread.start();
//主线程休眠期间,监控线程在执行监控操作
Thread.sleep(10000);
//为监控线程设置中断标志位
thread.interrupt();
//终止监控线程
//thread.terminate();
Thread.sleep(100000);
}
}
/**
* 如何优雅地终止线程池
*/
public class ThreadPoolDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executorService.submit(() -> {
try {
// 执行任务操作
System.out.println(Thread.currentThread().getName() + "正在执行任务...");
Thread.sleep(5000);
} catch (InterruptedException e) {
// 重新设置中断状态
Thread.currentThread().interrupt();
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + "任务执行完毕");
}
});
}
// 停止线程池接受新的任务,但不能强制停止已经提交的任务
executorService.shutdown();
// 等待线程池中的任务执行完毕,或者超时时间到达
boolean terminated = executorService.awaitTermination(3, TimeUnit.SECONDS);
if (!terminated) {
// 如果线程池中还有未执行完毕的任务,则调用线程池的shutdownNow方法,中断所有正在执行的任务
// 如果有还没开始执行的任务,则返回未执行的任务列表
List tasks = executorService.shutdownNow();
System.out.println("剩余未执行的任务数:" + tasks.size());
}
}
}
class Foo{
int age=0;
int name="abc";
}
final class Bar {
final Foo foo;
void setAge(int a){
foo.age=a;
}
}
//Foo线程安全
final class Foo{
final int age=0;
final String name="abc";
}
//Bar线程不安全
class Bar {
Foo foo;
void setFoo(Foo f){
this.foo=f;
}
}
ExecutorService es;
ThreadLocal tl;
es.execute(()->{
//ThreadLocal增加变量
tl.set(obj);
try {
// 省略业务逻辑代码
}finally {
//手动清理ThreadLocal
tl.remove();
}
});
public class GuardedObject {
//结果
private T obj;
//获取结果
public T get() {
synchronized (this) {
//没有结果等待 防止虚假唤醒
while (obj == null) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return obj;
}
}
//产生结果
public void complete(T obj) {
synchronized (this) {
//获取到结果,给obj赋值
this.obj = obj;
//唤醒等待结果的线程
this.notifyAll();
}
}
}
boolean changed = false;
// 自动存盘操作
void autoSave() {
synchronized (this) {
if (!changed) {
return;
}
changed = false;
}
// 执行存盘操作
// 省略且实现
this.execSave();
}
// 编辑操作
void edit() {
// 省略编辑逻辑
......
change();
}
// 改变状态
void change() {
synchronized (this) {
changed = true;
}
}
boolean inited = false;
synchronized void init(){
if(inited){
return;
}
//省略doInit的实现
doInit();
inited=true;
}
final ServerSocketChannel ssc=
ServerSocketChannel.open().bind(new InetSocketAddress(8080));
//处理请求
try{
while(true){
// 接收请求
SocketChannel sc=ssc.accept();
// 每个请求都创建一个线程
new Thread(()->{
try{
// 读Socket
ByteBuffer rb=ByteBuffer.allocateDirect(1024);
sc.read(rb);
//模拟处理请求
Thread.sleep(2000);
// 写Socket
ByteBuffer wb=(ByteBuffer)rb.flip();
sc.write(wb);
// 关闭Socket
sc.close();
}catch(Exception e){
throw new UncheckedIOException(e);
}
}).start();
}
}finally{
ssc.close();
}
ExecutorService es = Executors.newFixedThreadPool(200);
final ServerSocketChannel ssc = ServerSocketChannel.open().bind(new
InetSocketAddress(8080));
//处理请求
try{
while(true){
// 接收请求
SocketChannel sc=ssc.accept();
// 将请求处理任务提交给线程池
es.execute(()->{
try{
// 读Socket
ByteBuffer rb=ByteBuffer.allocateDirect(1024);
sc.read(rb);
//模拟处理请求
Thread.sleep(2000);
// 写Socket
ByteBuffer wb=
(ByteBuffer)rb.flip();
sc.write(wb);
// 关闭Socket
sc.close();
}catch(Exception e){
throw new UncheckedIOException(e);
}
});
}
}finally{
ssc.close();
es.shutdown();
}
public class BlockingQueueExample {
private static final int QUEUE_CAPACITY = 5;
private static final int PRODUCER_DELAY_MS = 1000;
private static final int CONSUMER_DELAY_MS = 2000;
public static void main(String[] args) throws InterruptedException {
// 创建一个容量为QUEUE_CAPACITY的阻塞队列
BlockingQueue queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
// 创建一个生产者线程
Runnable producer = () -> {
while (true) {
try {
// 在队列满时阻塞
queue.put("producer");
System.out.println("生产了一个元素,队列中元素个数:" + queue.size());
Thread.sleep(PRODUCER_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(producer).start();
// 创建一个消费者线程
Runnable consumer = () -> {
while (true) {
try {
// 在队列为空时阻塞
String element = queue.take();
System.out.println("消费了一个元素,队列中元素个数:" + queue.size());
Thread.sleep(CONSUMER_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(consumer).start();
}
}