1. 程式人生 > >java多線程

java多線程

bsp new 成績單 pan i++ sync say als exce

線程的同步和死鎖:

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多線程