Two ways to open threads

Source: Internet
Author: User

/**

  • Two ways to customize the execution unit
  • Difference
  • Runnable avoids the limitations of single inheritance
  • Runnable resources can be shared independently
  • How to find problems with multithreading
    1. Identify which code is multithreaded to run the code
    2. Identify what is shared data
    3. Identify which statements in multithreaded code are operations that share data
  • @author Wangshuang
  • /
    public class Test {
    public static void Main (string[] args) {
    /
    MyThread t0=new MyThread ();
    MyThread t1=new MyThread ();
    T0.start ();
    T1.start ();//200 tickets appear
    */
    T0.start ();//java.lang.illegalthreadstateexception

    /*MyRunnable r=new MyRunnable();Thread rt0 = new Thread(r);Thread rt1 = new Thread(r);rt0.start();rt1.start();*/

    }
    }
    /**

  • Mode 1 Inherits Thread
  • If you want to implement two windows to buy tickets,
  • MyThread t0=new MyThread ();
    MyThread t1=new MyThread ();
    T0.start ();
    T1.start ();//200 tickets appear
    If adding static in front of the tick solves the problem but the life cycle is too long, use mode 2
  • @author Administrator
  • /
    Class MyThread extends thread{
    /
    static plus static bad life cycle too long */int tick = 100;br/> @Override

    while (tick>0) {
    System.out.println (tick--);
    }
    }
    }
    /**

  • Mode 2 implements the Runnable interface
  • @author Administrator
  • */
    Class Myrunnable implements Runnable {
    int tick = 100;br/> @Override

    Synchronized (new Object ()) {
    while (tick>0) {
    System.out.println ("" +this.tostring ());
    System.out.println (Thread.CurrentThread (). GetName () + "" +tick--);
    }
    }
    }
    }

Two ways to open threads

Related Article

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.