Home >Java >javaTutorial >Memo for beginners to learn Java (3)
Today I started to learn the implementation of multi-threading in Java.
Threads are codes that can be executed in parallel and independently. The programs I wrote before could only do one thing, that is, only one thread. Multi-threaded programming is Program tasks can be divided into multiple parallel subtasks, which can be run simultaneously without interfering with each other. My understanding of multi-threading comes from fighting games. In fighting games, two-person fights are realized through two threads. Otherwise, how can you use your moves and I send my shock waves?
(January 18) Suddenly a question came to my mind and I would like to add. Is multi-threading what we usually call multi-tasking? My understanding is, You can say this if you can't.
Simply put, multi-threading provides a mechanism for parallel scheduling of multiple threads within a process, while multi-tasking provides a mechanism for running multiple processes within an operating system.
The basic principle of multi-tasking operating systems (such as Windows) is this: the operating system allocates the CPU time slice to multiple threads, and each thread is completed within the time slice specified by the operating system (note that the multiple threads here are belong to different processes). The operating system continuously switches from the execution of one thread to the execution of another thread, and so on. From a macro perspective, it seems that multiple threads are executing together. Since these multiple threads belong to different process, so from our point of view, it seems that multiple processes are executing at the same time, thus achieving multi-tasking. Whoops, what a mouthful.
As mentioned above, there is a clear difference between multi-threading and multi-tasking. But again Think about it, doesn’t implementing multi-threading in an application also rely on CPU allocation of time slices? Since the principle is the same, multi-threading can also be said to be multi-tasking.
After a Java program is started, there is already one thread During operation, we can use the following example to initially establish the actual impression of a thread
class testthread{
public static void main(String args[]){
Thread t=Thread.currentThread();
t.setName(" This Thread is running");
System.out.PRintln("The running thead:"+t);
try{
for(int i=0;i<5;i++)
{
System.out.println( "Sleep time"+i);
Thread.sleep(1000);//Suspending a thread means letting the thread rest for a while without occupying system resources, so other threads can continue. Thread here defaults to the main thread
}
}catch(InterruptedException e){System.out.println("thread has wrong");}
}
}
This is just one thread, so how do we implement multiple threads? And how do we let the thread do what I arrange it to do? What to do?
There are two ways to realize the construction of the thread body.
The first method is to continue to construct the thread body.
There is a Thread class in Java, and there is a function run() in this class, which records According to the operation to be completed by the thread, it is like the main function usually called main(). When the run() function is finished running, the thread ends. By continuing this class, we can define our own thread and tell it in the run function What it should do. The following program is a continuation of a SimpleThread class, using two threads to output HelloWorld.
public class TwoThread{
public static void main(String args[]){
new SimpleThread("HelloWorld1" ).start();//Create two thread instances, it’s that simple
new SimpleThread("HelloWorld2").start();
}
}
class SimpleThread extends Thread{ file://The real content is in Here
public SimpleThread(String str){
super(str);//super represents the direct parent class of the SimpleThread class, here is Thread
}
file://Everything we want the thread to do is here
public void run(){
for(int i=0;i<10;i++){
System.out.println(i+" "+getName());
try{
sleep((int)(Math.random() *1000));
}catch(InterruptedException e){}
}
System.out.println("Done!"+getName());
}
}
The result of running is that the two threads alternately display their respective HelloWorld ten times, the output is mixed together because the two threads are running at the same time. The second method is to construct the thread body through the startup interface. In any class that implements the startup interface, such as the twothread class below, Multi-threading can be achieved. All I need to do is add a run function to the definition of this class. The routine is as follows
class TwoThread implements Runnable{
TwoThread(){
Thread t1=Thread.currentThread();
t1 .setName("The first main thread");
System.out.println("The running thead:"+t1);
Thread t2=new Thread(this,"the second thread");//Pay attention to this here , it indicates that what the new thread, t2, will do is determined by this object, that is, by the run function of twothread
System.out.println("create another thread");
t2.start();// Calling this function will cause the thread to start executing from the run function
try{
System.out.println("first thread will sleep");
Thread.sleep(3000);
}catch(InterruptedException e){System.out.println ("first thread has wrong");}
System.out.println("first thread exit");
}
public void run()//Define the run() function, which is the new t2 in this program The thread will do
{
try{
for(int i=0;i<5;i++)
{
System.out.println("sleep time for thread 2:"+i);
Thread.sleep(1000);
}
}catch(InterruptedException e ){System.out.println("thread has wrong");}
System.out.println("second thread exit");
}
public static void main(String args[]){
new TwoThread(); //Trigger the constructor
}
}
The running result is as follows:
The running rhread:Thread[The first main thread,5,main]
create another thread
first thread will sleep
Sleep time for thread 2:0
Sleep time for thread 2:1
Sleep time for thread 2:2
first thread exit
Sleep time for thread 2:3
Sleep time for thread 2:4
second thread exit
Bullshit about other things. We noticed a lot Java programs have import statements at the beginning, which seem to be very similar to C's #include and Delphi's uses. Import is the keyword of Java and is responsible for transferring into the package. The package consists of a set of classes and interfaces and is used to manage large names. Space, a tool to avoid name conflicts.
Java provides many packages for us to use, mainly as follows:
java.applet
Classes for designing Applets
java.awt
Window tool package, including classes for generating GUI elements
java.io
File input and output class
java.lang
java language class, including: objects, threads, exception exits, systems, integers, origins, numbers, characters, etc.
java.net
Socket class and TCP/ip Related classes
java.util
Some program synchronization classes
...
In the evening, I took a rough look at the concept of Java classes. As a basic element of object-oriented programming, the idea of classes is more reflected in Java. C++ is more prominent. Unlike C++, which still maintains compatibility with procedural languages, Java programs only have classes, which are completely object-oriented. For example, the string "hello" is also an object, and we can call " Hello".equalsIgnoreCase() to determine whether it is the same as other strings. The main program Main that we usually see in C must also be encapsulated into a class in Java and referenced through the class. The basic properties of classes are in Java The embodiment is nothing more than overloading, continuation and polymorphism. Overloading refers to creating member functions with the same name and different parameters, which is horizontal. Continuation means inheriting variables and member functions from ancestor classes, which is vertical. Examples of polymorphism Generally speaking, when the program is running, instance variables can choose to appear as instances of the parent class or as instances of the subclass as needed.
Writing these things more will stimulate your brain more and remember them more firmly. This is to avoid being like the last time when I applied for a job, the examiner asked me what the properties of object-oriented are, and I couldn’t answer them all. It was really frustrating.
The above is the content of the memo (3) for newbies learning Java. , for more related content, please pay attention to the PHP Chinese website (www.php.cn)!