Java thread Two

Source: Internet
Author: User

/* 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.