1.join与interrupt的用法

class Sleeper extends Thread
{
private int duration;
public Sleeper(String name,int sleepTime)
{
super(name);
duration=sleepTime;
start();
}
public void run(){
try {
sleep(duration);
} catch (Exception e) {
System.out.println(getName()+" was interrupted."+"isInterrupted():"+isInterrupted());
return;
}
System.out.println(getName()+" has awakened");
}
} class Joiner extends Thread{
private Sleeper sleeper;
public Joiner(String name,Sleeper sleeper){
super(name);
this.sleeper=sleeper;
start();
}
public void run(){
try {
sleeper.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
System.out.println(getName()+" join completed");
}
} public class Joining {
public static void main(String[] args) {
Sleeper
sleepy=new Sleeper("Sleepy", 1500),
grumpy=new Sleeper("Grumpy", 1500);
Joiner
dopey=new Joiner("dopey", sleepy),
doc=new Joiner("doc", grumpy);
grumpy.interrupt();
}
}

2.未处理异常

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory; class ExceptionThread2 implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by " + t);
System.out.println("eh=" + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
} class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
// TODO Auto-generated method stub
System.out.println("cauth" + e);
}
} class HandlerThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t);
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("eh=" + t.getUncaughtExceptionHandler());
return t;
}
} public class CaptureUncaughtException {
public static void main(String[] args) {
ExecutorService exec = Executors
.newCachedThreadPool(new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}
//默认处理异常

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


public class SettingDefaultHandler {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new ExceptionThread());
}
}

3.(1)synchronized void f(){ /* ... */ }

(2)private Object syncObject=new Object();
       synchronized(syncObject){
          ...
        }

同步方法

4.同步方法

private Lock lock=new ReentrantLock();
private int i=0;
public int next(){
lock.lock();
try{
...
return i;
}
finally{
lock.unlock();
}
}

5.java.lang.ThreadLocal

线程本地存储

6.wait() 挂起线程  notifyAll() 唤醒wait()中挂起的线程

7.

ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new WaxOff(car));
exec.execute(new WaxOn(car));
TimeUnit.SECONDS.sleep(5);
exec.shutdownNow();//内部使用interrupt()中止线程池中的所有线程
//exec.shutdown();

8.单个的生产者、消费者

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

class Meal {
private final int orderNum;

public Meal(int orderNum) {
this.orderNum = orderNum;
}

public String toString() {
return "Meal " + orderNum;
}
}

class WaitPerson implements Runnable {
private Restaurant restaurant;

public WaitPerson(Restaurant r) {
restaurant = r;
}

public void run() {
try {
while (!Thread.interrupted()) {
//TimeUnit.SECONDS.sleep(3);
synchronized (this) {
while (restaurant.meal == null) {
wait();
}
}
System.out.println("Waitperson go " + restaurant.meal);
synchronized (restaurant.chef) {
restaurant.meal = null;
restaurant.chef.notifyAll();
}
}
} catch (InterruptedException e) {
//如果线程已经interrupted了,执行sleep就会进入InterruptedException,所以要加此异常捕获
System.out.println("WaitPerson interrupted");
}
}
}

class Chef implements Runnable {
private Restaurant restaurant;
private int count = 0;

public Chef(Restaurant r) {
restaurant = r;
}

public void run() {
try {
//TimeUnit.SECONDS.sleep(1);
while (!Thread.interrupted()) {
synchronized (this) {
while (restaurant.meal != null)
wait();
}
if (++count == 10) {
System.out.println("Out of food,closing");
restaurant.exec.shutdownNow();
}
System.out.println("Order up!");
synchronized (restaurant.waitPerson) {
restaurant.meal = new Meal(count);
restaurant.waitPerson.notifyAll();
}
//TimeUnit.MICROSECONDS.sleep(100);
}
} catch (InterruptedException e) {
//如果线程已经interrupted了,执行sleep就会进入InterruptedException,所以要加此异常捕获
System.out.println("Chef interrupted");
}
}
}

public class Restaurant {
Meal meal;
ExecutorService exec = Executors.newCachedThreadPool();
WaitPerson waitPerson = new WaitPerson(this);
Chef chef = new Chef(this);

public Restaurant() {
exec.execute(chef);
exec.execute(waitPerson);
}

public static void main(String[] args) {
new Restaurant();
}
}

9.已实现同步的队列集合

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit; class Toast {
public enum Status {
DRY, BUTTERED, JAMMED
} private Status status = Status.DRY;
private final int id; public Toast(int idn) {
id = idn;
} public void butter() {
status = Status.BUTTERED;
} public void jam() {
status = Status.JAMMED;
} public Status getStatus() {
return status;
} public int getId() {
return id;
} public String toString() {
return "Toast " + id + ": " + status;
}
} class ToastQueue extends LinkedBlockingDeque<Toast> {
} class Toaster implements Runnable {
private ToastQueue toastQueue;
private int count = 0;
private Random rand = new Random(47); public Toaster(ToastQueue tq) {
toastQueue = tq;
} public void run() {
try {
while (!Thread.interrupted()) {
TimeUnit.MICROSECONDS.sleep(100 + rand.nextInt(500));
Toast t = new Toast(count++);
System.out.println(t);
toastQueue.put(t);
}
} catch (InterruptedException e) {
System.out.println("Toaster interrupted");
}
System.out.println("Toaster off");
}
} class Butterer implements Runnable {
private ToastQueue dryQueue, butteredQueue; public Butterer(ToastQueue dry, ToastQueue buttered) {
dryQueue = dry;
butteredQueue = buttered;
} public void run() {
try {
while (!Thread.interrupted()) {
Toast t = dryQueue.take();
t.butter();
System.out.println(t);
butteredQueue.push(t);
}
} catch (InterruptedException e) {
System.out.println("Butter interrupted");
}
System.out.println("Butterer off");
}
} class Jammer implements Runnable {
private ToastQueue butteredQueue, finishedQueue; public Jammer(ToastQueue butterd, ToastQueue finished) {
butteredQueue = butterd;
finishedQueue = finished;
} public void run() {
try {
while (!Thread.interrupted()) {
Toast t = butteredQueue.take();
t.jam();
System.out.println(t);
finishedQueue.put(t);
}
} catch (InterruptedException e) {
System.out.println("Jammer interrupted");
}
System.out.println("Jammer off");
}
} class Eater implements Runnable {
private ToastQueue finishedQueue;
private int counter = 0; public Eater(ToastQueue finished) {
finishedQueue = finished;
} public void run() {
try {
while (!Thread.interrupted()) {
Toast t = finishedQueue.take();
if (t.getId() != counter++
|| t.getStatus() != Toast.Status.JAMMED) {
System.out.println(">>>> Error: " + t);
System.exit(1);
} else {
System.out.println("Chomp! " + t);
}
}
} catch (InterruptedException e) {
System.out.println("Eater interrupted");
}
System.out.println("Eater off");
}
} public class ToastOMatic {
public static void main(String[] args) throws InterruptedException {
ToastQueue dryQueue = new ToastQueue(), butteredQueue = new ToastQueue(), finishedQueue = new ToastQueue();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Toaster(dryQueue));
exec.execute(new Butterer(dryQueue, butteredQueue));
exec.execute(new Jammer(butteredQueue, finishedQueue));
exec.execute(new Eater(finishedQueue));
TimeUnit.SECONDS.sleep(5);
exec.shutdownNow();
}
}

10.输入输出管道

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; class Sender implements Runnable {
private Random rand = new Random();
private PipedWriter out = new PipedWriter(); public PipedWriter getPipedWriter() {
return out;
} public void run() {
try {
while (true) {
for (char c = 'A'; c <= 'Z'; c++) {
out.write(c);
TimeUnit.MILLISECONDS.sleep(rand.nextInt());
}
}
} catch (IOException e) {
System.out.println(e + " Sender write exception");
} catch (InterruptedException e) {
System.out.println(e + " Sender sleep interrupted");
}
}
} class Receiver implements Runnable {
private PipedReader in; public Receiver(Sender sender) throws IOException {
in = new PipedReader(sender.getPipedWriter());
} public void run() {
try {
while (true) {
System.out.println("Read: " + (char) in.read() + ".");
}
} catch (IOException e) {
System.out.println(e + " Receiver read exception");
}
}
} public class PipedIO {
public static void main(String[] args) throws Exception {
Sender sender = new Sender();
Receiver receiver = new Receiver(sender);
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(sender);
exec.execute(receiver);
TimeUnit.SECONDS.sleep();
exec.shutdownNow();
}
}

java多线程的使用2的更多相关文章

  1. 40个Java多线程问题总结

    前言 Java多线程分类中写了21篇多线程的文章,21篇文章的内容很多,个人认为,学习,内容越多.越杂的知识,越需要进行深刻的总结,这样才能记忆深刻,将知识变成自己的.这篇文章主要是对多线程的问题进行 ...

  2. Java多线程基础知识篇

    这篇是Java多线程基本用法的一个总结. 本篇文章会从一下几个方面来说明Java多线程的基本用法: 如何使用多线程 如何得到多线程的一些信息 如何停止线程 如何暂停线程 线程的一些其他用法 所有的代码 ...

  3. Java多线程系列--“JUC锁”03之 公平锁(一)

    概要 本章对“公平锁”的获取锁机制进行介绍(本文的公平锁指的是互斥锁的公平锁),内容包括:基本概念ReentrantLock数据结构参考代码获取公平锁(基于JDK1.7.0_40)一. tryAcqu ...

  4. Java多线程系列--“JUC锁”04之 公平锁(二)

    概要 前面一章,我们学习了“公平锁”获取锁的详细流程:这里,我们再来看看“公平锁”释放锁的过程.内容包括:参考代码释放公平锁(基于JDK1.7.0_40) “公平锁”的获取过程请参考“Java多线程系 ...

  5. Java多线程--让主线程等待子线程执行完毕

    使用Java多线程编程时经常遇到主线程需要等待子线程执行完成以后才能继续执行,那么接下来介绍一种简单的方式使主线程等待. java.util.concurrent.CountDownLatch 使用c ...

  6. Java多线程 2 线程的生命周期和状态控制

    一.线程的生命周期 线程状态转换图: 1.新建状态 用new关键字和Thread类或其子类建立一个线程对象后,该线程对象就处于新生状态.处于新生状态的线程有自己的内存空间,通过调用start方法进入就 ...

  7. java 多线程 1 线程 进程

    Java多线程(一).多线程的基本概念和使用 2012-09-10 16:06 5108人阅读 评论(0) 收藏 举报  分类: javaSE综合知识点(14)  版权声明:本文为博主原创文章,未经博 ...

  8. 一起阅读《Java多线程编程核心技术》

    目录 第一章 Java多线程技能 (待续...)

  9. 第一章 Java多线程技能

    1.初步了解"进程"."线程"."多线程" 说到多线程,大多都会联系到"进程"和"线程".那么这两者 ...

  10. java从基础知识(十)java多线程(下)

    首先介绍可见性.原子性.有序性.重排序这几个概念 原子性:即一个操作或多个操作要么全部执行并且执行的过程不会被任何因素打断,要么都不执行. 可见性:一个线程对共享变量值的修改,能够及时地被其它线程看到 ...

随机推荐

  1. docker学习3-虚拟网络模式

    一.虚拟机网络模式 在理解docker网络隔离前,先看下之前虚拟机里对网络的处理,VirtualBox中有4中网络连接方式: NAT Bridged Adapter Internal Host-onl ...

  2. ASP.NET Cookie 概述【转】

    来源:http://msdn.microsoft.com/zh-cn/library/ms178194(VS.80).aspx ASP.NET Cookie 概述 Cookie 提供了一种在 Web ...

  3. php download断点

    FileDownload.class.php <?php /** php下载类,支持断点续传 *   Date:   2013-06-30 *   Author: fdipzone *   Ve ...

  4. MvcPager2.0 中分页初始化失败的问题

    页面初始化时只有一页数据,或没数据时,出现分页控件初始化失败以及后续Ajax分页功能失效的问题, <div class="pagin"> <div class=& ...

  5. python pydoc

    pydoc是Python自带的模块,主要用于从python模块中自动生成文档,这些文档可以基于文本呈现的.也可以生成WEB 页面的,还可以在服务器上以浏览器的方式呈现! windows powersh ...

  6. Appium查找元素

    记录一些需要记忆的查找元素的内容: 1. driver.findElement(By.name("DELETE");   //We can use the DELETE text ...

  7. no ocijdbc11 in java.library.path linux

    no ocijdbc11 in java.library.path linux vi /etc/profile export ORACLE_HOME=/oracle/database/oracle/p ...

  8. 性能优化-查询最耗CPU的SESSION与SQL

    在linux 系统中 用top命令查出CPU最高的SPID,再将SPID给存储过程,可以查出该进程的SQLTEXT create or replace procedure pro_get_sqltex ...

  9. [nginx]Nginx禁止访问robots.txt防泄漏web目录

    关于robots.txt文件:搜索引擎通过一种程序robot(又称spider),自动访问互联网上的网页并获取网页信 息.您可以在您的网站中创建一个纯文本文件robots.txt,在这个文件中声明该网 ...

  10. 响应式布局设置--@media only screen and

    @media only screen and  only(限定某种设备) screen 是媒体类型里的一种 and 被称为关键字,其他关键字还包括 not(排除某种设备) /* 常用类型 */类型 解 ...