Implement multithreading by inheriting THEAD classes:
Advantages: Simple to write, if you need to access the current thread, just use this, no need to use the Thead.currentthread () method.
Disadvantage: Because this thread class has inherited the Thead class, no other classes can be inherited.
Sample code:
Copy Code code as follows:
Package org.frzh.thread;
public class Firstthread extends thread{
private int i;
To override the Run method, the method body of the Run method is the thread execution body
public void Run () {
for (; i < i++) {
When a thread class inherits the thread class, you can call the GetName method directly to get the current thread name
If you want to get the current thread, use this directly
Thread object's GetName method returns the name of the current thread
System.out.println (GetName () + "" + i);
}
}
public static void Main (string[] args) {
for (int i = 0; i < i++) {
Call the Thead CurrentThread method to get the current thread
System.out.println (Thread.CurrentThread (). GetName () + "" +i);
if (i = = 20) {
New Firstthread (). Start ();
New Firstthread (). Start ();
}
}
}
}
To run the result fragment:
We found that the value of I in two sub threads is not contiguous, and it seems to be inconsistent with the data that we are talking about that the child threads share directly. In fact, here we instantiate two child threads, each with its own instance variable i.
Using multithreading to implement Runable interface:
Advantage: The thread class only implements the Runable interface, so it can also inherit other classes;
In this case, you can enable multiple threads to share a target object, so it is ideal for multiple threads to handle the same resource, so that you can separate the CPU, code, and data to form a clear model and better embody object-oriented thinking.
Disadvantage: Programming is slightly complicated, and you must use the Thread.CurrentThread method if you want to access the current thread.
Sample code:
Copy Code code as follows:
Package org.frzh.thread;
public class Secondthread implements runnable{
private int i;
@Override
public void Run () {
TODO auto-generated Method Stub
for (; i < i++) {
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
}
}
public static void Main (string[] args) {
for (int i = 0; i < i++) {
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
if (i = = 20) {
Secondthread st = new Secondthread ();
New Thread (ST, "Child thread 1"). Start ();
New Thread (ST, "Child Thread 2"). Start ();
}
}
}
}
To run the result fragment:
As you can see, the I values at this time are continuously changing because threads 1 and 2 share the same target.