线程的四种状态及其转换

  同步代码块

  1)同步的前提:

  A.必须有两个或两个以上的线程

  B.必须保证同步的线程使用同一个锁。必须保证同步中只能有一个线程在运行。

  好处与弊端:解决了多线程的安全问题。多个线程需要判断锁,较为消耗资源。

public class RunnableTest implements Runnable {

 private int num = 100;
 Object obj = new Object();

 @Override
 public void run() {
  while (true) {
   synchronized (obj) {
    if (num > 0) {
     try {
      Thread.sleep(100);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println(Thread.currentThread().getName()
       + "----->" + num--);
    } else {
     break;
    }
   }
  }
 }

 public static void main(String args[]) {
  RunnableTest rt = new RunnableTest();
  Thread t1 = new Thread(rt, "新线程1");
  Thread t2 = new Thread(rt, "新线程2");
  Thread t3 = new Thread(rt, "新线程3");
  t1.start();
  t2.start();
  t3.start();
 }

}