Implement multi-threading by inheriting the Thead class:
Advantages: Simple to write. If you need to access the current thread, just use this instead of using the Thead.currentThread() method.
Disadvantage: Because this thread class has inherited the Thead class, it cannot inherit other classes.
Sample code:
Copy the code code as follows:
package org.frzh.thread;
public class FirstThread extends Thread{
private int i;
//Rewrite the run method. The method body of the run method is the thread execution body.
public void run() {
for (; i < 100; i++) {
//When the thread class inherits the Thread class, you can directly call the getName method to obtain the current thread name.
//If you want to get the current thread, use this directly
//The getName method of the Thread object returns the name of the current thread
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
//Call Thead's currentThread method to get the current thread
System.out.println(Thread.currentThread().getName() + " " +i);
if (i == 20) {
new FirstThread().start();
new FirstThread().start();
}
}
}
}
Running result snippet:
We found that the values of i in the two sub-threads are not continuous, which seems inconsistent with what we said about the direct sharing of data by the sub-threads. In fact, here we instantiate two sub-threads, each with its own instance variable i.
Using multi-threading that implements the Runable interface:
Advantages: The thread class only implements the Runable interface, so it can also inherit other classes;
In this case, multiple threads can share a target object, so it is very suitable for multiple threads to process the same resource, so that the CPU, code and data can be separated to form a clear model and better reflection. Object-oriented thinking.
Disadvantages: Programming is slightly complicated. If you want to access the current thread, you must use the Thread.currentThread method.
Sample code:
Copy the 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 < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; 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();
}
}
}
}
Running result snippet:
It can be seen that the i value at this time changes continuously because threads 1 and 2 share the same target.