为了准备华为时找到的一些关于多线程的例子,再次发表一下:
ava中的线程
Java中实现多线程的类有两种方法
1.扩展java.lang.Thread类,用它覆盖Thread类的run方法。
2.生成实现java.lang.Runnable接口的类并将其它的实例与java.lang.Thread实例相关联
Thread类最重要的方法是run方法。run方法是新线程执行的方法
线程的几个重要的时间段:
·开始线程的初始化
·线程开始执行main()瞬间
·线程开始执行start()的瞬间
·start()创建一个新线程并返回main()的瞬间
·新线程的初始化
·新线程开始执行run()的瞬间
·每个线程结束的不同瞬间
注意新线程的初始化,它对run()的执行,和它的结束都与开始线程的执行同时发生。
警告
一个线程调用start()后,在run()方法退出前并发调用那方法将导致start()掷出一个java.lang.IllegalThreadStateException对象。
线程间发信
Object 类为此提供了三个函数:wait()、notify() 和 notifyAll()
当对一个线程调用 wait() 时,该线程就被有效阻塞,只到另一个线程对同一个对象调用 notify() 或 notifyAll() 为止
notify仅唤醒一个线程并允许它去获得锁,notifyAll是唤醒所有等待这个对象的线程并允许它们去获得对象锁
在调用wait的时候,线程自动释放其占有的对象锁,同时不会去申请对象锁。当线程被唤醒的时候,它才再次获得了去获得对象锁的权利。
wait就是等待这个对象的同步锁,不过调用这个方法必须先获得这个对象的同步锁
notify:唤醒在等待该对象同步锁的线程
首先是生产者和消费者问题
- class Stor {
- String name = "";
- boolean full = false;
- public synchronized void setProduction(String name) {
- while (full) {
- try {
- this.wait();
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- }
- full = true;
- System.out.println("ddddddddddddddd");
- this.notify();
- }
- public synchronized void getProduction() {
- while (!full) {
- try {
- this.wait();
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- }
- full = false;
- System.out.println("ffffffffffffffffff");
- this.notify();
- }
- }
- class Custome extends Thread {
- Stor stor;
- public Custome(Stor stor) {
- this.stor = stor;
- }
- public void run() {
- while (true) {
- stor.getProduction();
- }
- }
- }
- class Productor extends Thread {
- Stor stor;
- public Productor(Stor stor) {
- this.stor = stor;
- }
- public void run() {
- while (true) {
- stor.setProduction("test");
- }
- }
- }
- public class Product {
- public static void main(String[] arg) {
- Stor stor = new Stor();
- Custome custome = new Custome(stor);
- custome.start();
- Productor productor = new Productor(stor);
- productor.start();
- }
- }
一个关于死锁的例子:
- public class Test {
- public static void main(String[] args) {
- final Object resource1 = "resource1";
- final Object resource2 = "resource2";
- // t1 tries to lock resource1 then resource2
- Thread t1 = new Thread() {
- public void run() {
- // Lock resource 1
- synchronized (resource1) {
- System.out.println("Thread 1: locked resource 1");
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- }
- synchronized (resource2) {
- System.out.println("Thread 1: locked resource 2");
- }
- }
- }
- };
- // t2 tries to lock resource2 then resource1
- Thread t2 = new Thread() {
- public void run() {
- synchronized (resource2) {
- System.out.println("Thread 2: locked resource 2");
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- }
- synchronized (resource1) {
- System.out.println("Thread 2: locked resource 1");
- }
- }
- }
- };
- // If all goes as planned, deadlock will occur,
- // and the program will never exit.
- t1.start();
- t2.start();
- }
- }