JAVA中的多线程——死锁
了解死锁,是为了开发中避免死锁。
- /*
- * 死锁
- * 同步中嵌套同步,锁却不同
- *
- * */
- class Ticket3 implements Runnable {
- private int tick = 1000;
- Object object = new Object();
- boolean flag=true;
- public void run() {
- if(flag){
- while (true) {
- synchronized (object) {
- show1();
- }
- }
- }
- else {
- while(true)
- show1();
- }
- }
- public synchronized void show1(){
- synchronized (object) {
- if (tick > 0) {
- }
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- // TODO: handle exception
- }
- System.out.println(Thread.currentThread().getName() + "sale:" + tick--);
- }
- }
- }
- public class DeadLockDemo {
- public static void main(String args[]) {
- Ticket3 ticket1 = new Ticket3();
- Thread t1 =new Thread(ticket1);
- Thread t2=new Thread(ticket1);
- t1.start();
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- // TODO: handle exception
- }
- ticket1.flag=false;
- t2.start();
- }
- }