线程死锁:
package com.thread;
public class TestDeadLock extends Thread {
static Object o1 = new Object(), o2 = new Object();
int flag = 0;
public void run() {
if(flag == 0){
synchronized (o1) {
System.out.println("tdl1锁定了o1");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
System.out.println("tdl1---success");
}
}
}
if(flag == 1){
synchronized (o2) {
System.out.println("tdl2锁定了o2");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1){
System.out.println("tdl2---success");
}
}
}
}
public static void main(String[] args) {
TestDeadLock tdl1 = new TestDeadLock();
TestDeadLock tdl2 = new TestDeadLock();
tdl1.flag = 0;
tdl2.flag = 1;
tdl1.start();
tdl2.start();
}
}
生产消费:
package com.thread;
public class ProducerCustomer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer pr = new Producer(ss);
Customer cr = new Customer(ss);
Thread pr1 = new Thread(pr);
Thread pr2 = new Thread(pr);
Thread cr1 = new Thread(cr);
Thread cr2 = new Thread(cr);
pr1.setName("---生产者P1");
pr2.setName("---生产者p2");
cr1.setName("消费者c1");
cr2.setName("消费者c2");
pr1.start();
pr2.start();
cr1.start();
cr2.start();
}
}
/**
* 生产消费对象
*/
class Product{
private int id;
public Product(int id) {
this.id = id;
}
public String toString() {
return "Product的编号: " + id;
}
}
/**
* 存储产品的仓库
*/
class SyncStack{
//索引,其大小是库存量
int index = 0;
Product[] arrPd = new Product[10];
//生产者生产
public synchronized void push(Product pd){
//如果仓库满了
while(index == arrPd.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
arrPd[index] = pd;
index ++;
}
//消费者消费
public synchronized Product pop(){
//仓库没有存货
while(index == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
return arrPd[--index];
}
}
class Producer implements Runnable{
SyncStack ss = null;
public Producer(SyncStack ss){
this.ss = ss;
}
public void run() {
for(int i = 1; i <= 10; i++){
Product pd = new Product(i);
ss.push(pd);
System.out.println(Thread.currentThread().getName()+"生产了"+pd.toString());
try {
//随机睡眠一个时间
Thread.sleep((int)Math.random()*100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Customer implements Runnable{
SyncStack ss = null;
public Customer(SyncStack ss){
this.ss = ss;
}
public void run() {
for(int i = 1; i <= 10; i++){
Product pd = ss.pop();
System.out.println(Thread.currentThread().getName()+"消费了"+pd.toString());
try {
//随机睡眠一个时间
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}