This article shares with you the specific methods of implementing the Runnable method of Java multi-threading for your reference. The specific content is as follows
(I) Steps
1. Define and implement Runnable interface
2. Overwrite the run method in the Runnable interface and store the code that the thread wants to run in the run method.
3. Create thread objects through the Thread class.
4. Pass the subclass object of the Runnable interface as actual parameters to the constructor of the Thread class.
Why do we talk about the constructor of the Runnable interface subclass object passed to Thread? Because the object to which the custom method belongs is a subclass object of the Runnable interface.
5. Call the start method of the Thread class to start the thread and call the Runnable interface subclass run method.
(II) Thread-safe shared code block problem
Purpose: Is there any security problem with the program? If so, how to solve it?
How to find the question:
1. Identify which codes are multi-threaded running code.
2. Clearly share data
3. Clarify which statements in the multi-threaded code operate to 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(100); } } } } 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 in the second way, put the synchronization code synchronized in the modification method.
class Bank{ private int sum; public synchronized void add(int n){ Object obj=new Object(); sum+=n; try{ Thread.sleep(10); }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(100); } } } 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 and method to deal with in a class.
2. Rewrite the run method in the class that implements Runnable to call the method to handle the problem in the already defined class.
Accept the object of the class to handle the problem in the synchronized block.
3. Define multiple threads to execute in the main method.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.