java 线程二

来源:互联网 发布:视频噪声消除软件 编辑:程序博客网 时间:2024/05/23 18:05
/*多线程死锁问题。*/class Tacket implements Runnable //extends Thread{private static int sum=200;//sum是共享数据,放在堆内存中,所有线程访问这一个共享数据。在一个线程运行完之后,共享数据要被同步修改。Object obj=new Object();boolean flag=true;public void run(){if(flag){while(true){synchronized(obj){show();}}}elsewhile(true)show();}public synchronized void show(){synchronized(obj)   //同步代码块,存放需要被同步的代码。{if(sum>0)   //操作共享数据{try{Thread.sleep(10);}catch (InterruptedException e){}System.out.println(Thread.currentThread().getName()+"run"+sum--);  //操作共享数据}}}}class  TacketDemo2{public static void main(String[] args) {Tacket t=new Tacket();   //只创建了一个Ticket对象,所有线程共享此对象的数据,包括总票数sumThread t1=new Thread(t);//将Runnable接口的子类对象作为参数传递给Thread类的构造函数,目的是线程运行子类对象中的run方法。Thread t2=new Thread(t);t1.start();try{Thread.sleep(10);}catch(InterruptedException e){}t.flag=false;t2.start();//Thread t3=new Thread(t);//Thread t4=new Thread(t);//t3.start();//t4.start();//t1.start();//出现异常,因为线程t1已经被开启,无需再被开启。System.out.println("Hello World!");}}

0 0
原创粉丝点击