Before entering the thread object on the Java platform, I inserted two basic concepts based on some of the questions in the basic article (a).
[Concurrency and parallelism of threads]
In a single CPU system, system scheduling can only allow one thread to run at a time, although this kind of debugging mechanism has many forms (most is the time slice wheel patrol mainly), but in any case, it is called concurrency (concurrent) by constantly switching the threads that need to be run. In a multiple-CPU system, you can have more than two threads running at the same time, which allows more than two threads to run concurrently, called parallelism (parallel).
In all the subsequent discourses, please understand that I cannot define terms such as concurrency and parallelism with the most accurate words, but in my experience I can tell you how it is, if you see some of the "standard" documents that I said are not the same, as long as the meaning is consistent, then you should not be picky.
[Java Thread Object]
Now let's start with the Java thread object.
In Java, there are two ways to start a thread. The first is the start () method that invokes the thread instance directly, and the second is
Pass the runable instance to a thread instance and call its start () method.
As has been said before, thread objects and threads are two completely different concepts. Here we go deep again and generate an instance of a thread that does not mean that the thread is started. The start thread is that the thread that started the instance on a thread object, and when that thread ends, it does not disappear immediately.
I don't have to say much about the basics that can be seen from many books. Since it's the basics, I'm also focusing on what I can't read from normal documents. So what I'm going to focus on in this section is the difference between two thread objects that produce threading patterns.
class MyThread extends Thread{
public int x = 0;
public void run(){
for(int i=0;i<100;i++){
try{
Thread.sleep(10);
}catch(Exception e){}
System.out.println(x++);
}
}
}
If we generate an instance of Mythread and then call its start () method, the corresponding thread of this instance is generated:
public class Test {
public static void main(String[] args) throws Exception{
MyThread mt = new MyThread();
mt.start();
}
}
Needless to say, it will print out 0 to 99, and now we're going to play a little bit of tricks:
public class Test {
public static void main(String[] args) throws Exception{
MyThread mt = new MyThread();
mt.start();
System.out.println(101);
}
}
Needless to say, in the basic article (a) We know that because of the single CPU, usually print 101 first, and then print 0 to 99. But we can control the thread to make it run the way we want it to:
public class Test {
public static void main(String[] args) throws Exception{
MyThread mt = new MyThread();
mt.start();
mt.join();
System.out.println(101);
}
}