zoukankan      html  css  js  c++  java
  • java的死锁学习

    学习java的死锁写的代码

    也是看书上的然后自己敲了一个

    <span style="font-size:18px;">package synchronization.java.test;
    /**
     * 关于java中线程死锁样例
     * 在学习操作系统的时候有线程死锁可是也仅仅是理解也没有亲自己主动手敲过
     * 如今学java既然学到这里了就敲了一个简单的以进餐为例的代码
     * @author hello
     * @version 8
     */
    public class DeadLock {
         static String knife="餐刀",fork="叉子"; 
          static class A extends Thread{
        	 public void run(){  //重写的方法
        		 synchronized(knife){//
        			 System.out.println("小明拿到了"+knife+"等待"+fork+".........");
        			 try {
    					Thread.sleep(100);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
        			 synchronized(fork){//这是用来測试的其实因为死锁了这一步永远也不会出现
        				 System.out.println("小明又拿到"+fork);
        			 }
        		 }
        	 }
         }
         static class B extends Thread{
        	 public void run(){
        		 synchronized(fork){
        			 System.out.println("小华拿到了"+fork+"等待"+knife+".........");
        			 try {
    					Thread.sleep(100);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
        			 synchronized(knife){//这是用来測试的其实因为死锁了这一步永远也不会出现
        				 System.out.println("小华又拿到"+knife);
        			}
        		 }
        	 }
         }
         static class Demo extends  Thread{
        	 public Demo(){
        		 this.setDaemon(true);
        	 }
        	 public void run(){
        		 while(true){
        			 try {
    					Thread.sleep(1000);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}//这个线程一直在执行
        			 System.out.println("程序正在执行中......");
        		 }
        	 }
        	 
         }
    	public static void main(String[] args) {
    	     new A().start();//因为是静态的直接new即可
    	     new B().start();
    	     new Demo().start();
    
    	}
    
    }
    </span>


  • 相关阅读:
    HTTP断点续传 规格严格
    Java Shutdown 规格严格
    linux 命令源码 规格严格
    JTable调整列宽 规格严格
    linux 多CPU 规格严格
    Hello can not find git path 规格严格
    Kill 规格严格
    拜拜牛人 规格严格
    Swing 规格严格
    Debugging hangs in JVM (on AIX but methodology applicable to other platforms) 规格严格
  • 原文地址:https://www.cnblogs.com/jhcelue/p/7117442.html
Copyright © 2011-2022 走看看