Java多线程02_状态,同步,通信

1、线程的状态

  • 新建:线程创建

  • 就绪:使用start()方法启动线程

  • 运行:开始执行run()方法

    • 阻塞
      • 挂起:Thread的 yield()方法,让出此次CPU分配的时间,给其他线程使用,若再次分配到自己,那将继续执行 yield()方法之后的代码
      • 睡眠:Thread的sleep()方法,休眠结束后,继续运行
      • 等待 :Object的wait()方法,需要使用Object的notify()方法唤醒,继续运行
      • 等待:子线程中使用Thread的join()方法,父线程需要等待子线程运行结束后再继续运行
      • IO输入
      • ····
  • 死亡:run()方法运行结束

2、线程同步(synchronized—Lock)

synchronized

同步方法
synchronized修饰普通方法,锁住的是对象实例,自己调用时等待
代码示例:

public synchronized void test1() {
		
	System.out.println(Thread.currentThread().getName() + "进入该方法");
	try {
		Thread.sleep(2000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	System.out.println(Thread.currentThread().getName() + "睡眠结束");
}

synchronized修饰静态方法,锁住的是class对象,所有实例等待
代码示例:

public synchronized static void test2() {
	System.out.println(Thread.currentThread().getName() + "进入该方法");
	try {
		Thread.sleep(2000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	System.out.println(Thread.currentThread().getName() + "睡眠结束");
}

同步块
结构:

Synchronized (取得锁的对象){
//要锁定的代码
}

锁的对象为对象实例时
代码示例:

//方式一
public void test3() {
	synchronized (this) {
		System.out.println(Thread.currentThread().getName() + "进入该方法");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "睡眠结束");
	}
}
//方式二
public void test4(SynchronizedDemo s) {
	synchronized (s) {
		System.out.println(Thread.currentThread().getName() + "进入该方法");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "睡眠结束");
	}
}

锁的对象为class对象时
代码示例:

public void test5(Class<?> c) {
	synchronized (c) {
		System.out.println(Thread.currentThread().getName() + "进入该方法");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "睡眠结束");
	}
}

synchronized方式的总结:

  • synchronized修饰普通方法、代码块锁this、以及我们代码块锁对象实例,他们的锁就是锁的对象实例
  • synchronized修饰静态方法、代码块锁class对象,他们的锁就是锁类对象
  • synchronized锁住对象实例的时候,有线程在使用synchronized方法,其他线程不能访问该对象的其他synchronized方法,但是可以访问非synchronized方法
  • synchronized锁住class对象的时候,有线程在使用static synchronized方法, 其他线程不能访问该对象的其他static synchronized方法, 但是可以访问synchronized方法和非synchronized方法

Lock

锁块
代码示例:

Lock l = new ReentrantLock();
//直接加锁  l.lock();
//判断是否有锁  没有进入if 并加锁
if(l.tryLock()) {
			
	System.out.println(Thread.currentThread().getName()+"获得加锁");
			
	Long s = new Date().getTime();
	System.out.println("执行代码块");
	Long e = new Date().getTime();
	System.out.println("运行时间:"+(e-s));
			
	//释放锁
	l.unlock();
	System.out.println(Thread.currentThread().getName()+"释放锁");
}else {
	System.out.println(Thread.currentThread().getName()+"获取锁失败");
}

synchronized与lock的区别

  1. 首先synchronized是java内置关键字,在jvm层面, Lock是个java类,
  2. synchronized会自动释放锁,而Lock必须手动释放锁
  3. Lock可以让等待锁的线程响应中断,而synchronized不会, 线程会一直等待下去
  4. 通过Lock可以知道线程有没有拿到锁,而sylichronized不能 。
  5. Lock能提高多个线程读操作的效率
  6. synchronized能锁住类.方法和代码块,而Lock是块范围内的,Lock锁适合大量同步的代码的同步问题,synchronized锁适 合代码少量的同步问题。
  7. Lock的等待按照先来的进集合中排队,synchronized是无序的抢线程

死锁

假如线程A取得了对象锁,并执行程序代码时,线程A有可能需要再取得另一个对象锁才可以继续执行程序。但不幸地,另一个对象锁被其他的线程(假如是B)所拥有,而B线程也需要A线程所拥有的对象锁。此时,两个线程会处于饥饿状态,等待对方释放出对象锁,而导致彼此都无法往下执行,这种情况称为死锁。

代码示例:

public class ThreadDeathLock implements Runnable {
	Object o1;
	Object o2;
	int i;

	public ThreadDeathLock() {
		super();
	}

	public ThreadDeathLock(Object o1, Object o2, int i) {
		super();
		this.o1 = o1;
		this.o2 = o2;
		this.i = i;
	}

	public void test1() {
		synchronized (o1) {
			System.out.println(Thread.currentThread().getName() + "获取object1锁");
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "等待获取object2锁");
			synchronized (o2) {
				System.out.println(Thread.currentThread().getName() + "获取object2锁");
			}
		}
	}
	public void test2() {
		synchronized (o2) {
			System.out.println(Thread.currentThread().getName() + "获取object2锁");
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "等待获取object1锁");
			synchronized (o1) {
				System.out.println(Thread.currentThread().getName() + "获取object1锁");
			}
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(i == 0) {
			test1();
		}
		if(i == 1) {
			test2();
		}
	}
	
	public static void main(String[] args) {
		Object o1 = new Object();
		Object o2 = new Object();
		
		Runnable r1 = new ThreadDeathLock(o1,o2,0);
		Runnable r2 = new ThreadDeathLock(o1,o2,1);
		
		Thread t1 = new Thread(r1,"r1");
		Thread t2 = new Thread(r2,"r2");
		t1.start();
		t2.start();
	}
}

3、线程之间的相互通讯(wait-notify 机制)

  • 为避免轮流检测,Java提供了一个精心设计的线程间通信机制,使用wait()、notify()和notifyAll()方法 。

  • 这些方法是作为 Object 类中的 final 方法实现的。

  • 这三个方法仅在 synchronized 方法中才能被调用。

  • wait()方法告知被调用的线程退出监视器并进入等待状态,直到其他线程进入相同的监视器并调用 notify( ) 方法。

  • notify( ) 方法通知同一对象上第一个调用 wait( )线程。

  • notifyAll() 方法通知调用 wait() 的所有线程,具有最高优先级的线程将先运行。

生产者和消费者示例

//定义UseData代表仓库中的货物
class UseData {
	private int data;
	boolean flag = false;

	public synchronized int getData() {
		while (!flag) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		data--;
		flag = false;
		System.out.println("取出后:" + data);
		notify();
		return data;
	}

	public synchronized void setData() {
		while (flag) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		data++;
		flag = true;
		System.out.println("增加后:" + data);
		notify();
	}
}

//定义消费者
class Consumer implements Runnable {
	UseData UC;

	Consumer(UseData UC) {
		this.UC = UC;
		Thread t = new Thread(this);
		t.start();
	}

	public void run() {
		while (true) {
			UC.getData();
			try {
				Thread.sleep((int) (Math.random() * 1000) * 5);
			} catch (InterruptedException e) {
			}

		}
	}
}

//定义生产者
class Producer implements Runnable {
	UseData UC;

	Producer(UseData UC) {
		this.UC = UC;
		Thread t = new Thread(this);
		t.start();
	}

	public void run() {
		while (true) {
			UC.setData();
			try {
				Thread.sleep((int) (Math.random() * 1000) * 5);
			} catch (InterruptedException e) {
			}
		}
	}
}

//主程序用于测试
public class PC1 {
	public static void main(String[] args) {
		UseData uc = new UseData();
		new Producer(uc);
		new Consumer(uc);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值