多线程

最近琢磨了一下多线程,把整理的东西与大家分享一下吧~ 

创建线程共有两种方式,如下

方法一:

public class PrimeThread extends Thread {

    long minPrime;

    PrimeThread(long minPrime) {

        this.minPrime = minPrime;

    }

    public void run() {

        //写需要多线程执行的代码

    }

}

new PrimeThread(143).start();

方法二:

public class PrimeRun implements Runnable {

    long minPrime;

    PrimeRun(long minPrime) {

        this.minPrime = minPrime;

    }

    public void run() {

        //需要多线程执行的代码

    }

}

new Thread(new PrimeRun(143)).start();

 

死锁情况: 两个线程执行下一步都需要对方持有的锁

public class SynTest implements Runnable{

    public boolean flag;

    @Override

    public void run() {

       while(true){

           if (flag) {

              synchronized(Object.class){

                  System.out.println("if true 1 = "+this);

                  try {

                     Thread.sleep(10);

                  } catch (InterruptedException e) {

                  }

                  synchronized(SynTest.class){

                     System.out.println("if true 2 = ");

                  }

              }

           }

           else{

              synchronized(SynTest.class){

                  System.out.println("if false 1 = "+SynTest.class);

                  try {

                     Thread.sleep(10);

                  } catch (InterruptedException e) {

                  }

                  synchronized (Object.class) {

                     System.out.println("if false 2 = ");

                  }

              }

           }

       }     

    }  

}

 

线程状态:

 

重点介绍:

    1. synchronized修饰的方法持有的锁是this,synchronized修饰的静态方法用的锁是本类名称.class

    2. 线程优先级1—10,数字越大,优先级越高

    3. wait()方法冻结线程并释放锁,sleep()方法冻结线程但不释放锁

    4. JDK1.5以后出现了Lock接口,可以替代synchronized关键字,并且用Condition接口将wait(),notify(),notifyAll()方法封装成对象,一个Lock上可以挂多个Condition,这样解决了notifyAll()方法每次都唤醒所有锁上线程的问题,可以选择性的唤醒需要唤醒的线程

posted on 2013-10-05 20:14  仙剑情缘  阅读(870)  评论(1编辑  收藏  举报