java多线程的使用2

时间:2024-05-22 23:05:20

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();
}
}