/* multithreaded deadlock problem. */class Tacket implements Runnable//extends thread{private static int sum=200;//sum is a shared data that is placed in heap memory and all threads access this shared data. After a thread has finished running, the shared data is modified synchronously. 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)///synchronous code block, which stores the code that needs to be synchronized. {if (sum>0)//operation shared Data {try{thread.sleep (10);} catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "Run" +sum--); Operation shared data}}}}class tacketdemo2{public static void Main (string[] args) {tacket t=new tacket (); Only one ticket object is created, and all threads share data for this object, including the total number of votes Sumthread t1=new Thread (t), or the subclass object of the Runnable interface as a parameter to the thread class's constructor. The intent is that the thread runs the Run method in the subclass object. 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 ();//The exception occurs because the thread T1 has been turned on without being opened again. System.out.println ("Hello world!");}}
Java thread Two