Hello.
Yes, students in this class and will create our first multithreaded program.
It is time to put our theoretical knowledge on practice and learn new things.
We'll start from understanding of threat lifecycle and in which states our threat may be and when will
jump to practical examples.
You'll have enough knowledge to understand that.
And this lesson I will show you how to create a threat with five different ways.
We are going to learn such basic laws for multithreaded in general threat and one of the most important
interfaces.
Runnable.
While showing you examples, I will focus your attention on main properties of threat class to describe
each state.
And once we Iran's threats, we will learn with you how we can interact execution of a threat.
We'll discuss methods that are deprecated for a long time already and that you never should use.
And also we'll talk about proper ways of threat interaction.
Today, we're going to have a lot of good examples.
And as we will go over the examples, I will also explain specifics of some methods and behavior of
threats.
Let's start.
And as I said before, let's start from the understanding the whole lifecycle of a threat is considered
to be a new one.
We just created an object of a threat.
And you know that in Java, everything is an object.
That's why threat of execution is also an object to run a threat.
We need to start massive because mass that creates a separate threat of execution within the Java process.
After that threat is in the running state.
In this state, we can make our threat not run by turning our threat into waiting state or block state.
During this course, we will discuss all these scenarios, for example, when threat is blocked and
when it's waiting for now, you need just to understand that running threat may be put on pause and
getting back to running state again as engineers will learn how to do this.
Sometimes threats waiting their chance to update a shared resource.
Sometimes we want to make a threat, wait until other threats will adjust it of our shared resource.
And the last possible state of our threat is a Terminator's state.
This state tells us that threat finished its execution or it was interrupted.
Is it clear now when you're no threat?
Life-cycle it is time to write our first.
Just read an application I open file was named first just writing program.
I have main message here.
Let me go line by line and explain you each role here.
You can see that the first thing that I do here, I declare a variable of type Runnable and initialize
it with new object of type default.
Runnable.
Let me open source code of Runnable type, because you see this time the first time in this course,
as you can see, this is an interface from the Java version.
What does a functional interface was only one abasic mass with name.
Right.
We see that this method returns nassan and return type is void.
This is exactly the method that we need to implement and where we need to put a code that will be executed
in the separate thread to have separate thread, we need to have instructions about what this thread
is supposed to do and these instructions should be written somewhere.
This is exactly the method that will be executed by thread.
Let's now check the source code of a default runnable we see as a default Runnable implements Runnable
interface.
Basically, this is my custom clause that gives implementation to run Macel inside this matter.
I print such text to console.
I'm a new threat.
My name is and here I call static method on class will learn this class in a minute.
But just to finish explanation of this line, current threat is a static method of threat class that
returns the reference to the threat object.
And depending on where this method is invoked, we receive the reference to the object of current threat.
And after that I just call that name method that returns is a name of the threat.
I want to bring this text to console to prove that we have separate threat of execution.
One will run our app.
But before doing that, let's investigate threat glass.
Let me open the source code of this class.
The first thing is that you can notice here is that threat also implements Runnable.
What does this mean?
This means that the object of threat type also may be executed as a separate threat.
And this class also has implementation of around MassArt.
Let's look at it.
As we can see, the first things that object will try to do is to check whether we have target field
initialized.
And if yes, then we'll call run Masset on that object.
And if not, then we'll just do nothing.
Target Field has Runnable type and we can see even Kermanshah above this field.
This is something.
What will be around so as you can understand, we can do two things here.
We can pass Runnable object to the threat glass or we can override run Masad in Third-Class, we can
pass Runnable to this class.
We are constructor.
We have really a lot of different versions of constructor for this type.
And one of the constructor is to accept and initialize target field to store the reference to the Runnable
object.
Interesting thing to notice here is that this constructor invokes another version of constructor.
It passes in reference to the REDgroup.
We'll discuss a little bit later.
What does it reference to our Runnable object name of the thread, which consists of the word thread
dash and the sequential number.
Is it a static variable name thread in it?
No, that is incremented every time when the next threatener method and the last argument is a stack
size zero because according to the recommendation, in case this argument is zero, we have no requirement
for specific text size for this new threat.
And the new constructor Interent calls new constructor that passes to more arguments.
New and true new value is supposed to cover such constructor argument as access control context and
true value is the flag to indicate whether we need to inherit initial values for inheritable threat
logos from the construction threat.
Let me explain what these things meant.
Access control context is a type that is used to create objects that make system access decisions based
on the context it encapsulates.
Check permission Massada that is invoked in the context that access control context encapsulates inside
is allowed to process was access to resources or access control exception.
Anyway, this is not the topic for the first lesson of not just reading.
And this is not what you will use on a daily basis directly while working with me.
Just read it.
But just in order to let you know.
Regarding the second argument inherits read.
Locals do not pay a lot of attention to this one.
And this moment will cover concept of threat locals and inheritable threat local separately, but ensured
this flag is to tell threat whether we need to inherit values from inheritable threat local from the
construction threat.
And basically after that we proceed with construction of our threat of execution.
Besides the construction of Runnable that we have just discussed, we have also different constructors
that initializes other properties of threat object, for example, threat that takes Runnable and access
control context, constructor that takes REDgroup and Runnable also another popular constructor for
the bag and purposes is constructor with Runnable and string.
String represents the name of the threat and other different variations, including constructors with
taxes and boolean flag to indicate the state of the inherited threat.
The locals flag.
What are the properties?
The threat glass half.
If we would scroll to the top of this file, will find properties that we also may use during the configuration
of the threat.
You already know about threatening property.
By the way, here is also new keyword for you.
Volatile will cover it.
Do in the separate lesson we have priority property.
This is a from one to 10 that will be used by threat scheduler to decide what threat is more important
to work with.
So this next, however, we never can rely on the priority property when we have concurrent threat executed.
Let's call this recommendation, but not mandatory direction to follow for threats.
Catala What is a threat?
Skalla It is part of GM that decides which threats should run.
Also, it decides which threats should wait, how it is.
This is a great question, but probably not for the first practical move.
This riding lesson will also cover this topic separately.
The next property here is on by default.
It is false.
We will discuss later in this course what demons threats are interrupted.
Flag is used to indicate where the threat is interrupted and we need to stop its execution or we need
to proceed execution of a threat.
Let in this lesson.
I will also show you how to interact with this property.
Maxfield's here used by Jovian.
We will not focus our attention on them in this lesson.
And probably the one property that we did not talk yet is a threat.
The group this object is used to groups threats to gather in one group support group forms a three and
every threat except a regional threat.
The group has a parent.
There are also some specific self-locking mechanism for threat in that group, but probably will cover
this in a separate lesson.
And it looks like that Tetragon high level of.
You officer red class and its properties definitely as more things to learn here, but we'll do it gradually
and with practical examples, case by case.
Now, let's get back to the demo file here.
You can see that I created a threat object and positive reference to the Runnable object.
Why option was a separate class might be needed in this case.
You can declare some files if needed.
Also, you can declare constructors and pass external resources to the new objects if needed, because
by default, ranma, it doesn't take anything as Masset argument.
And here's just an example of constructor initialization of the state of this object.
If we want, we can pass any external object to the constructor and use the state of our runnable object
in one method if needed.
In such a way you can just share the resource that we shared with this thread.
This is basically the first way to create a threat object that is ready to be executed and that is in
your state.
The next way is another variation of the first one.
Instead of creating type that implements Runnable, we can just pass instance of anonymous class.
You can see here that I have similar method implemented.
Basically nothing special to highlight here.
And to be honest, this way of creating threat is not very popular.
The next way to great threat is to extend a new class from the threat and all around Massett, if you
remember when we were you in threat object, we saw that there is nothing to execute by default if we
didn't pass the reference to the Runnable object.
That's why so radically we can just override one method.
You can see that the current class extends threat clause and we overwrite one method here.
And after that, the main method is simply create the object of the first sorting program type.
That's it.
While this option often described in the literature, don't recommend it to you this way.
Why?
Because he extends that class just to overwrite one method.
Probably it is not the best approach from the single responsibility principle point of view.
For such purposes we have Runnable type and we can use it to give implementation to run Macit.
The fourth way to prepare a threat for execution is to use lambda expression to implement around Macit.
She can see that I created lambda function.
That takes no arguments and returns nassan.
Basically I just print the same text and the last, but not least for today, is the way preparing A
was MassArt reference.
I have a static method declared in this class with name execute that takes no parameters and that brings
the same text to cancel.
I just passing method reference here that meets the definition of Runnable interface.
It doesn't take any arguments and it returns nassan the same as around Massett.
In case you are not familiar with lambda functions and method references in Java, but you want to learn
that.
Check my functional programming course for Java InGenius.
We have really a lot of examples that the next thing that you see in this line and a sprinkling of the
current threat to console and for the sake of example, call run Nassib.
Remember, Run Masset doesn't start as a threat of execution, only start MassArt starts separate thread.
But if you would call directly around MassArt, you would just execute run MassArt synchronously.
And after that I call starts MassArt on each thread that we created here.
Let's run the program to see what we have got in the console in the first line with the printed text
from my main threat here you can see the text current threatening is and its name is Main Man is the
name of the first read that we have in our Java application is the next line is a result of invocation
of FRAND method.
And as you can see, threatening is still man.
That proves that invocation of method doesn't actually start a new threat.
And to start a new threat, we need to start Macit after you can see multiple lines with different names
of a threat.
That is exactly what is returned by getting the same method on the current threat involved from the
threat.
And you remember that by default, naming convention for each threat is threat word and sequential number
of a threat.
Can you understand now how to run your threat in real life?
You often use executor's to run and manage.
Your threats will learn executor's later in this course.
But what we have learned in this lesson, this is basics that you need to understand before moving further.
Now, what do we know how?
To start the threat, let's learn how to interact and stop its execution.
I have separate file for that was name interrupt them is interesting app that will help you to understand
how threat interception works.
Let's start from the main mast.
The first thing that I do here, create a task for execution.
I implement it runnable interface in this class for the sake of this demo and not having multiple classes
in this example.
I will show you around Massud in the minute after this.
I create a threat object and start a threat and I won't let the main threat sleep for two seconds and
interrupt my task after two seconds.
How I can do this?
I invoke sleep masset on the threat object.
This method takes a number of milliseconds as Masset argument.
Two seconds are equal to two thousand milliseconds.
Sleep method is our law that in threat class.
Let's look at the threat clause.
Source code.
We have to sleep massas here.
One was milliseconds only and another one takes two arguments, milliseconds and nanoseconds.
To be honest, I never used sleep mass.
It was nanoseconds, but still it is good to know that such method exists.
Let's get back to our demo file, another really user friendly interface of making sure that sleep is
to use time unit in from Javitz.
You can current package.
This enum represents time duration at the given unit of granularity and provides methods to convert
across units and perform timing and delay operations.
In these units, for example, you may perform such operations as making Meinzer slip, and the interface
allows us to not calculate milliseconds and convert them between seconds and other time units.
One unit.
But we can just take time units that we need and parse the value of the specific time unit that we need.
For example, here is a line similar to the one above.
It also uses milliseconds time unit and here is a line that use a second time unit.
And I'm just saying two seconds.
To be honest, in my opinion, using this API is more preferable.
And after this line, my main threat is in on the running state, in wait in state and the one threat
is awaiting as a threat may interrupt it.
That's why Slakey method maestro so called interrupted exception.
And that's why Compiler makes us handle this exception case to describe how a system should behave in
case somebody will interrupt this thread.
In this example, nobody will interrupt main threat but still interrupted.
Exception is checked.
That's why we need Searls declaration here in Maine method because for the sake of this demo, I don't
want to create try catch block here.
After that I print a console that I interact as a threat.
To interrupt as a threat.
We should call interrupt method interrupt method interruption flag inside the threat object.
That flag basically has two possible values, true or false.
With the help of this method, we can change the state of the interaction flag inside the threat and
the last line and my main threat is print and leave in the console.
Let's now look at our task and understand how interrupt.
Masset interrupts execution of the threat.
I open one method.
I print text that indicates that I entered one method and the threat is about to execute Vork method.
I invoke Vork method.
Let's look at it now.
Work method is that was the infinite loop.
After that we just print one word.
Verkin in f close.
I check if threat is interrupted is interrupted.
Matthew Chance is a state of the interaction flat and in case somebody from as a threat called MassArt
interrupt like we did in our main threat, then this method will return.
True.
Right now you already know what is done by interrupt and by is interrupted masses.
But why do we need interrupted?
Macit interrupted Massata returns also boolean value and return state of the interaction flac but it
also clears it and return it back to false.
So in case what uncommon this line and will executed interruption flag will be turned back to false
again.
To interrupt this thread I will keep this line commanded and we'll just leave it as an example for you.
By the way, I encourage you to download this service code example from the GitHub and run it locally
on your computer.
By doing this, you can play with values and comment and comment the lines that you are interested in
and as always, service code examples in attachments to this lesson.
OK, so now I believe.
The difference between these three methods interact is interrupted and interrupted.
Now pay attention that threat is moved to the white state because and will sleep mass at here.
And by the way, no matter how long sleep will be, I put one millisecond here for sleep.
But still, it is enough to interrupt the threat.
What will happen?
One threat will be a sleep take into account.
I'm in this safe block because interrupted FLAC is equal to true and the threat is invading state.
My threat will be interrupted and interrupted.
Exceptions will be thrown.
This line will not be executed never because interrupted exception will be thrown this mass Atheros
interrupted exception without any handlin to the upper level.
And here we should print interrupted in the work method and return from around Macit.
As you can see here, I have tried Kedge Block because sleep mass my throat checked exception and work
method doesn't handle this potential exception inside.
Let's run this program now for two seconds.
Program will bring to console working until threat will be interrupted and once it is interrupted,
let's see what we have.
The first thing that happened is threat interruption and even after that you can see that I printed
reconvert.
That is because I just changed interaction flac and I still need to wait until the threat will be in
a waiting mode.
This text in the main living tells us that Main Street finished its execution and after that we see
that we enter it if block.
And here is a status of interrupted flac.
It is equal to true.
The next step in our execution is entering the catch block and print and that threat was interrupted
in the work.
MassArt.
That's it.
So the rule of thumb, when you're creating all rain app, think about what is a logical point in your
thread to allow other threats to interrupt it.
In case you have such possibility to introduce this point, do it.
Usually you would let your threat fall asleep.
After all, resources are adjusted and state of the system is consistent.
In this case, there is no harm to interrupt the threat.
There are some methods that you should never use and that are marked as deprecated but not removed from
Janicki only because of the backwards compatibility.
Ziya, stop, suspend and resume.
These are dangerous masses in terms they are stop, suspend or resume threat execution instantly without
bothering.
What process is happening right now inside the threat, taking into account not all operations at ATOMIC
and performed with one single operation of updating data in the memory.
You can start somewhere in the middle of data processing in your threat.
At the meantime, resource will be updated as a threat.
And when you will resume execution, you may end up with not consistent state of your objects.
We will talk about atomic operations in adolescence, but I believe you understood that stopping a suspension
and after that resume and execution of the threat in case it is made some calculation process is not
the best idea.
And one more interesting and lasting for today's lesson.
Probably you saw one comment line here where I invoke June Masset.
What is it?
Let me uncommented first and run up one more time.
What's changed now in this version line?
Zatarain's in the main Leesville will always be printed.
Lost.
Why?
Because Join Masset also put our main threat in great state until this threat will be completely finished.
So I gave a command with this line to join.
This thread does a current one.
That's why my app will wait until Perry's threat will be completely executed during Masad.
Also, Masroor interrupted exception, taking into account it puts current threat wait in state and
other threats might interrupt this threat while it is innervate state.
Is it clear?
Basically, that's all what I wanted to share with you in this lesson.
Let's recap what we have learned today.
In this lesson, we learned the life cycle of the threat and how state of the threat is changed from
the new disseminated.
We learned five ways how to run a threat.
Also in this lesson, we performed over a year of threat class.
Now, you know, main properties of this type, we learned a radical interface.
Now you know how to use it to execute a separate threat.
And at the end of the lesson, we learned how to interrupt threat.
Hope you enjoyed the lesson and you like the examples.
We still have a lot of other things to learn, but.
I think that they will have enough information to remember, make sure you understand this lesson before
moving further, because multithreaded is not the easiest topic.
And we need to be very careful with understanding each concept in sequential order, because it would
be hard to understand one thing without understanding the previous one.
Thanks a lot for your attention.
Have a great day and see you in the next lesson.