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