java并发笔记
2015-05-30 22:58
483 查看
1.java的中断机制
java的中断机制就是为了让java的线程退出的一种机制,通过改变线程的状态,Thread提供了thread.interrupt方法使线程中断,然后线程可以抛出interruptedException使线程退出,或者在run()方法中判断线程的状态(isRuppted)方法,判断是否继续执行,从而使线程可以退出。
2.线程的休眠和恢复
使用sleep方法可以是当前线程进入睡眠,过了指定时间后会自动恢复。如果这个时候打断线程,会抛出InterruptException.
3.等待另外线程的终止
使用join()方法
Eg:
static class LocalSourceLoader implements Runnable{
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 {
}
5.线程中异常的处理
非运行时异常和运行时异常
/**
*
*/
package thread;
import java.lang.Thread.UncaughtExceptionHandler;
/**
* @author JianJiang
*
*/
public class Test1 {
}
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(); }
}
相关文章推荐
- java多线程和并发包入门示例
- Java阻塞队列SynchronousQueue实现并发
- Java并发的四种风味:Thread、Executor、ForkJoin和Actor
- 超越线程池:Java并发并没有你想的那么糟糕
- Java中的五种同步辅助类
- java并发 java7之fork-join框架
- Java线程:Callable和Future
- Java线程:锁对象Lock-同步问题更完美的处理方式
- Java线程:Condition-线程通信更高效的方式
- java并行,并发,串行,同步,异步,阻塞,非阻塞,同步阻塞,同步非阻塞,异步阻塞,异步非阻塞
- Java 并发专题 :FutureTask 实现预加载数据 在线看电子书、浏览器浏览网页等
- current包下ReentrantReadWriteLock的使用
- current包下Semaphore的使用
- current包下CyclicBarrier的使用
- java 并发 - 运行多个任务并执行第一个结果
- java 并发 - 带返回结果的任务
- Java 并发 (锁)
- Java锁是如何保证数据可见性的
- Java 并发编程内部分享PPT分享
- Java并发编程:CountDownLatch、CyclicBarrier和Semaphore