Java 多线程的同步

来源:互联网 发布:成绩统计分析软件 编辑:程序博客网 时间:2024/05/16 10:09

4.代码块与函数间的同步

class ThreadDemo1{public static void main(String [] args){TestThread tt = new TestThread();new Thread(tt).start();try{Thread.sleep(1);}catch(Exception e){}tt.str = new String("method");new Thread(tt).start();}}class TestThread implements Runnable//extends Thread{int tickets = 100;String str = new String("");public void run(){if(str.equals("method")){while(true){sale();}}else{while(true){synchronized(this){if(tickets > 0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+ " is sailing ticket " + tickets--);}}}}}public synchronized void sale(){if(tickets > 0){try{Thread.sleep(10);}catch(Exception e){}System.out.print("sale():");System.out.println(Thread.currentThread().getName()+ " is sailing ticket " + tickets--);}}}


原创粉丝点击