A
Steps:
1. Define implementation Runnable interface
2. Overwrite the Run method in the Runnable interface to store the code that the thread is running in the Run method.
3. Create thread objects through the thread class.
4. Pass the subclass object of the Runnable interface as the actual argument to the constructor of the thread class.
Why do you want to talk about the Runnable interface's subclass object being passed to the thread's construction method. Because the object to which the custom method belongs is the subclass object of the Runnable interface.
5. Call the Start method of the thread class to open the thread and invoke the Runnable interface subclass Run method.
(ii) thread-Safe shared code block issues
Objective: Whether the program has security problems and, if so, how to solve them.
How to find a problem:
1. Identify which code is multithreaded to run the code.
2. Clear sharing of data
3. Identify which statements in the multithreaded run code are operations that share data.
Class bank{
private int sum;
public void Add (int n) {
sum+=n;
System.out.println ("sum=" +sum);
}
Class Cus implements runnable{
private Bank B=new Bank ();
public void Run () {
synchronized (b) {for
(int x=0;x<3;x++)
{
b.add ();
}}}} Public
class bankdemo{public
static void main (String []args) {
Cus c=new Cus ();
Thread t1=new thread (c);
Thread t2=new thread (c);
T1.start ();
T2.start ();
}
Or the second way, place the synchronization code synchronized in the cosmetic method.
Class bank{
private int sum;
Public synchronized void Add (int n) {
object Obj=new object ();
Sum+=n;
try{
Thread.Sleep (ten);
} catch (Exception e) {
e.printstacktrace ();
}
System.out.println ("sum=" +sum);
}
Class Cus implements runnable{
private Bank B=new Bank ();
public void Run () {for
(int x=0;x<3;x++)
{
b.add
}}} public class bankdemo{public
static void main (String []args) {
Cus c=new Cus ();
Thread t1=new thread (c);
Thread t2=new thread (c);
T1.start ();
T2.start ();
}
Summarize:
1. Define the problem to be handled in a class, method.
2. In the class that implements Runnable, rewrite the Run method to invoke the method in the class that is already defined to handle the problem.
In the synchronized block, accept the object of the class to handle the problem.
3. In the main method, define multiple threads to execute.