java多線程中的生產者與消費者模式:
首先有一個阻塞隊列,生產者將生產的東西放到隊列裏,消費者再從隊列中取。當隊列中的東西數量達到其容量就發生阻塞。java
import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; public class UseBlockingQueue { private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);//1是隊列容量,超過就會阻塞。 // new PriorityBlockingQueue<>(); // new LinkedBlockingQueue<>(); // new ArrayBlockingQueue<>(10); private static class Producer extends Thread { @Override public void run() { Random random = new Random(20191116); while (true) { try { int message = random.nextInt(100); queue.put(String.valueOf(message));//將消息放入隊列中 System.out.println("放入消息: " + message); Thread.sleep(random.nextInt(3) * 100);//睡眠 } catch (InterruptedException e) { e.printStackTrace(); } } } } private static class Customer extends Thread { @Override public void run() { Random random = new Random(20191116); while (true) { try { String message = queue.take();//從隊列中取走消息 System.out.println("收到消息: " + message); Thread.sleep(random.nextInt(3) * 100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { Thread producer = new Producer(); Thread customer = new Customer(); producer.start(); customer.start(); } }
synchronized關鍵字修飾:給對象加鎖,保證線程安全,若是CPU發生任意調度,也不會線程不安全。安全
public class MyQueue2 { private int[] array = new int[2]; private volatile int size; private int front; private int rear; private Object full = new Object(); private Object empty = new Object(); public void put(int message) throws InterruptedException { while (size == array.length) { synchronized (full) { full.wait(); } } synchronized (this) { array[rear] = message; rear = (rear + 1) % array.length; size++; } synchronized (empty) { empty.notify(); } } public synchronized int take() throws InterruptedException { while (size == 0) { synchronized (empty) { empty.wait(); } } int message; synchronized (this) { message = array[front]; front = (front + 1) % array.length; size--; } synchronized (full) { full.notify(); } return message; } }
線程間的通訊
public class ThreadDemo {
public static void main(String[] args){
class Person{
public String name;
private String gender;
public void set(String name,String gender){
this.name =name;
this.gender =gender;
}
public void get(){
System.out.println(this.name+"...."+this.gender);
}
}//Person類 有兩個屬性 兩個方法
final Person p =new Person();//new一個Person類對象p
new Thread(new Runnable(){//匿名線程
public void run(){//覆寫run方法
int x=0;
while(true){
if(x==0){
p.set("張三", "男");
}else{
p.set("lili", "nv");
}
x=(x+1)%2;
}
}
}).start();
new Thread(new Runnable(){
public void run(){
while(true){
p.get();
}
}
}).start();//啓動一個匿名線程
}
}多線程