Java multithreading--Creating threads

Source: Internet
Author: User

1. Create a thread

There are two ways to create threads in Java: Using the thread class and using the Runnable interface. A thread instance needs to be established when using the Runnable interface. Therefore, regardless of whether a thread is established either through the thread class or the Runnable interface, an instance of the thread class or its subclasses must be established. Thread constructor:

    • public Thread ();
    • Public Thread (Runnable target);
    • Public Thread (String name);
    • Public Thread (Runnable target, String name);
    • Public Thread (Threadgroup Group, Runnable target);
    • Public Thread (Threadgroup Group, String name);
    • Public Thread (Threadgroup Group, Runnable Target, String name);
    • Public Thread (Threadgroup Group, Runnable Target, String name, long stackSize);

method One: Inherit the thread class override the Run method The code is as follows:


public class ThreadDemo1 {
public static void Main (string[] args) {
Demo d = new demo ();
D.start ();
for (int i=0;i<60;i++) {
System.out.println (Thread.CurrentThread (). GetName () +i);
}

}
}
Class Demo extends thread{
public void Run () {
for (int i=0;i<60;i++) {
System.out.println (Thread.CurrentThread (). GetName () +i);
}
}
}


Method Two: The code is as follows:

public class ThreadDemo2 {
public static void Main (string[] args) {
Demo2 d =new Demo2 ();
Thread t = new Thread (d);
T.start ();
for (int x=0;x<60;x++) {
System.out.println (Thread.CurrentThread (). GetName () +x);
}
}
}
Class Demo2 implements runnable{
public void Run () {
for (int x=0;x<60;x++) {
System.out.println (Thread.CurrentThread (). GetName () +x);
}
}
}

Java multithreading--Creating threads

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.