java并发笔记

1.java的中断机制
java的中断机制就是为了让java的线程退出的一种机制,通过改变线程的状态,Thread提供了thread.interrupt方法使线程中断,然后线程可以抛出interruptedException使线程退出,或者在run()方法中判断线程的状态(isRuppted)方法,判断是否继续执行,从而使线程可以退出。

2.线程的休眠和恢复
使用sleep方法可以是当前线程进入睡眠,过了指定时间后会自动恢复。如果这个时候打断线程,会抛出InterruptException.

3.等待另外线程的终止
使用join()方法
Eg:
static class LocalSourceLoader implements Runnable{

    @Override
    public void run() {
        System.out.println("begin load LocalSourceLoader....");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("end load LocalSourceLoader....");
    }
}

static class NetWorkSourceLoader implements Runnable{

    @Override
    public void run() {
        System.out.println("begin load NetWorkSourceLoader....");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("end load NetWorkSourceLoader....");
    }
}

public static void main(String[] args) {

    LocalSourceLoader localSourceLoader = new LocalSourceLoader();

    NetWorkSourceLoader netWorkSourceLoader = new NetWorkSourceLoader();

    Thread thread1 = new Thread(localSourceLoader,"localSourceLoader");

    Thread thread2 = new Thread(netWorkSourceLoader,"netWorkSourceLoader");

    thread1.start();
    thread2.start();

    try {
        thread1.join();
        thread2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.printf("Main :load success %S",new Date());
}

4.守护线程
守护线程优先级比较低,其他线程没有执行时,才会执行,守护线程结束后,jvm也就结束程序。守护线程可以用来处理收尾的工作任务。
Eg:
/**
*
*/
package thread;

import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.hamcrest.core.Every;

/**
* @author JianJiang
*
*/
public class Test1 {

static class Event {

    /**
     * Date of the event
     */
    private Date date;

    /**
     * Message of the event
     */
    private String event;

    /**
     * Reads the Date of the event
     * 
     * @return the Date of the event
     */
    public Date getDate() {
        return date;
    }

    /**
     * Writes the Date of the event
     * 
     * @param date
     *            the date of the event
     */
    public void setDate(Date date) {
        this.date = date;
    }

    /**
     * Reads the message of the event
     * 
     * @return the message of the event
     */
    public String getEvent() {
        return event;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Event [" + (date != null ? "date=" + date + ", " : "")
                + (event != null ? "event=" + event : "") + "]";
    }

    /**
     * Writes the message of the event
     * 
     * @param event
     *            the message of the event
     */
    public void setEvent(String event) {
        this.event = event;
    }

}

static class WriterTask extends Thread {

    private AtomicInteger atomicInteger = new AtomicInteger();

    private Deque<Event> deque;

    public WriterTask(Deque<Event> deque) {
        this.deque = deque;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            Event event = new Event();
            event.setDate(new Date());
            event.setEvent(String.format("The thread %s has generated an event",Thread.currentThread().getId()));
            deque.addFirst(event);
            System.out.println("添加元素:"+event);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

static class CleanTask extends Thread {

    private Deque<Event> deque;

    public CleanTask(Deque<Event> deque) {
        this.deque = deque;
        setDaemon(true);
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {

        while (true) {
            Date date = new Date();
            clean(date);
        }

    }


    /**
     * Method that review the Events data structure and delete
     * the events older than ten seconds
     * @param date
     */
    private void clean(Date date) {
        long difference;
        boolean delete;

        if (deque.size()==0) {
            return;
        }

        delete=false;
        do {
            Event e = deque.getLast();
            difference = date.getTime() - e.getDate().getTime();
            if (difference > 3000) {
                System.out.printf("Cleaner: %s\n",e.getEvent());
                deque.removeLast();
                delete=true;
            }   
        } while (difference > 10000);
        if (delete){
            System.out.printf("Cleaner: Size of the queue: %d\n",deque.size());
        }
    }




}


public static void main(String[] args) {

    Deque<Event> deques = new ArrayDeque<>();

    WriterTask writerTask1 = new WriterTask(deques);

    WriterTask writerTask2 = new WriterTask(deques);

    WriterTask writerTask3 = new WriterTask(deques);

    CleanTask cleanTask = new CleanTask(deques);

    writerTask1.start();

    writerTask2.start();

    writerTask3.start();

    cleanTask.start();
}

}

5.线程中异常的处理
非运行时异常和运行时异常

/**
*
*/
package thread;

import java.lang.Thread.UncaughtExceptionHandler;

/**
* @author JianJiang
*
*/
public class Test1 {

static class Thread1 extends Thread{

    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        Integer.parseInt("sss");
    }
}


static class ExceptionHandler implements UncaughtExceptionHandler{

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.printf("An exception has been captured\n");
        System.out.printf("Thread: %s\n",t.getId());
        System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage());
        System.out.printf("Stack Trace: \n");
        e.printStackTrace(System.out);
        System.out.printf("Thread status: %s\n",t.getState());
    }
}

public static void main(String[] args) {
    Thread1 t = new Thread1();
    t.setUncaughtExceptionHandler(new ExceptionHandler());
    t.start();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
嗨!很高兴回答你关于Java并发编程的问题。请问你想知道什么方面的内容呢?我可以分享一些学习笔记和建议给你。 1. 并发编程基础:了解并发编程的基本概念,如线程、进程、锁、同步等。学习Java中的并发编程模型以及相关的API,如Thread、Runnable、Lock、Condition等。 2. 线程安全性:学习如何保证多线程环境下的数据安全性,了解共享资源的问题以及如何使用同步机制来防止数据竞争和并发问题。 3. 线程间的通信:掌握线程间的通信方式,如使用wait/notify机制、Lock/Condition等来实现线程的协调与通信。 4. 并发容器:学习并发容器的使用,如ConcurrentHashMap、ConcurrentLinkedQueue等。了解它们的实现原理以及在多线程环境下的性能特点。 5. 并发工具类:熟悉Java提供的并发工具类,如CountDownLatch、CyclicBarrier、Semaphore等,它们可以帮助你更方便地实现线程间的协作。 6. 并发编程模式:学习一些常见的并发编程模式,如生产者-消费者模式、读者-写者模式、线程池模式等。了解这些模式的应用场景和实现方式。 7. 性能优化与调试:学习如何分析和调试多线程程序的性能问题,了解一些性能优化的技巧和工具,如使用线程池、减少锁竞争、避免死锁等。 这些只是一些基本的学习笔记和建议,Java并发编程是一个庞大而复杂的领域,需要不断的实践和深入学习才能掌握。希望对你有所帮助!如果你有更具体的问题,欢迎继续提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值