java多线程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程相关的知识,希望对你有一定的参考价值。
线程的同步和死锁:
public class Child { public void say(){ System.out.println("给我玩具,我就给你成绩单!"); } public void get(){ System.out.println("孩子得到玩具!"); } }
public class Father { public void say(){ System.out.println("给我成绩单,我就给你玩具!"); } public void get(){ System.out.println("父亲得到成绩单!"); } }
public class DeadTreadDemo implements Runnable { private static Father father = new Father(); private static Child child = new Child(); boolean flag = false; public void run(){ if(flag){ synchronized(father){ father.say(); try{ Thread.sleep(500); } catch(Exception e){ e.printStackTrace(); } synchronized(child){ father.get(); } } } else { synchronized(child){ child.say(); try{ Thread.sleep(500); } catch(Exception e){ e.printStackTrace(); } synchronized(father){ child.get(); } } } } }
public class TestDt { public static void main(String[] args) { DeadTreadDemo dd1 = new DeadTreadDemo(); DeadTreadDemo dd2 = new DeadTreadDemo(); dd1.flag = true; dd2.flag = false; new Thread(dd1).start(); new Thread(dd2).start(); } }
精灵线程:
public class RunnableDemo implements Runnable{ private String name; private int ticket = 5; public RunnableDemo(String name){ this.name = name; } // 精灵线程 public void run(){ for(int i=1;i<=5;i++){ synchronized(this){ if(ticket>0){ try{ Thread.sleep(1000); } catch(Exception e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "卖票:" + ticket--); } } //System.out.println(Thread.currentThread().getName() + "运行了:" + i); } } public static void main(String[] args) { RunnableDemo rd1 = new RunnableDemo("aaa"); new Thread(rd1).start(); new Thread(rd1).start(); } }
以上是关于java多线程的主要内容,如果未能解决你的问题,请参考以下文章