java--Thread--Problem sets brocade

Source: Internet
Author: User
Tags thread class

An advantage of an anonymous class is that it provides easy access to external local variables.
The premise is that the external local variables need to be declared final. (JDK7 will not be needed later)

======================

Synchronization Method 1: Normal type

Synchronization Method 2: Write the keyword in the object method, use this

Synchronization Method 3: Before the method, plus the modifier synchronized, the effect is equivalent to Method 2

==================

The title of the search file content synchronization

Change the practice-find file contents to multi-threaded find file contents
The idea of the original exercise is to traverse all the files, and when traversing to the file is. java, look for the contents of this file, after the search is complete, and then traverse the next file

Now adjust this idea through Multithreading:
Traverse all files, when traversing to the file is. java, create a thread to find the contents of this file, do not wait for the thread to end, continue to traverse the next file

Package Zsc.czy.zhonghe;import Java.io.file;import Java.io.filereader;public class Findcontent {public static void Mai                N (string[] args) {file F = new File ("D:/test");    Search (F, "Hello"); public static void Search (File F, String search) {System.out.println (f);//d:\find.txt System.out.prin TLN (F.getabsolutepath ());//System.out.println (F.getname ());//find.txt if (F.isfile ()) {if (f.getn                                        Ame (). toLowerCase (). EndsWith (". Java")) {new Thread (new Runnable () {                        @Override public void Run () {String filecontent = readfileconent (f); if (Filecontent.contains (search)) {System.out.printf ("Find sub-target string%s, in file:%s%n", sea                        RCH, F);                            }}). Start (); }} if (F.isdirectory ()) {file[] fs = F.liStfiles ();            for (File file:fs) {search (File,search); }}} private static String readfileconent (File f) {try (FileReader fr = new FileReader (f);)            {char[] c = new char[(int) f.length ()];            Fr.read (c);            string s = new string (c);        return s;        } catch (Exception e) {return null; }    }}
Topic 2--Hero Recharge

Heroes have the ability to put a skill called: Wave fist-a du Gen.
It can be sent once every second, but only 3 times in a row.

After 3 times, it needs to be charged for 5 seconds, full, and then continue to send.

Package Zsc.czy.thread;public class Hero {String name;    int hp;    int damage;    Public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public int gethp () {return HP;    } public void sethp (int hp) {this.hp = HP;    } public int Getdamage () {return damage;    } public void Setdamage (int damage) {this.damage = damage;    } public boolean Isdead () {return 0 >= hp? True:false;        The public void Attackhero (Hero h) {try {//) in order to indicate that the attack takes time, each attack pauses 1000 milliseconds thread.sleep (1000);        } catch (Exception e) {e.printstacktrace ();        } h.hp-= damage;        System.out.format ("%s is attacking%s,%s's blood programmed%.0f%n", name, H.name, H.name, H.HP);        if (H.isdead ()) {System.out.println (H.name + "dead");    }} int totaltime = 3; public void Adugen () {when (true) {for (inti = 0; i < TotalTime;                i++) {System.out.printf ("Wave boxing%d%n", i + 1);                try {thread.sleep (1000); } catch (Exception e) {//Todo:handle Exception}} SYSTEM.OUT.P            Rintln ("Charge at the beginning of 5 Seconds");            try {thread.sleep (5000);            } catch (Interruptedexception e) {e.printstacktrace ();        }}} public static void Main (string[] args) {Hero h = new Hero ();        H.name = "Red Doll";    H.adugen (); }}
Topic 3--Crack Password
    1. Generates a random string with a length of 3 and takes the string as a password

    2. Create a hack thread, use the exhaustive method, match this password

    3. Create a log thread that prints all the strings used to match, this log thread is designed to be a daemon thread

Tip: The hack thread puts the possible passwords generated by the brute-lifting method in a container, and the log thread constantly takes out the possible passwords from this container and prints them out. If the container is found to be empty, rest for 1 seconds, and if found not empty, keep it out and print.

==============================

HashMap is not strictly possible to store null--not a thread-safe class
Hashtable strict

ArrayList is non-thread safe
Vector is a thread-safe class

====================

Topic 4-Thread-safe mystack

Using a non-thread-safe collection to thread-safe, another way to complete the exercise-thread-safe mystack

Topic 5--Deadlock

3 synchronization objects A, B, c
3 Threads T1,t2,t3

Deliberately design the scene so that these 3 threads deadlock each other

I'm not a successful designer. Package Zsc.czy.thread;public class Sisuo {public static void main (string[] args) {final Hero Ahri        = new Hero ();        Ahri.name = "Nine-tailed demon fox";        Final Hero Annie = new Hero ();        Annie.name = "Anne";        Final Hero leqing = new Hero ();        Annie.name = "Li Qing";                    Thread t1 = new Thread () {public void run () {//Possession nine tail demon fox synchronized (Ahri) {                    System.out.println ("T1 already occupies nine tail demon fox");                    try {//Pause 1000 milliseconds, another thread has enough time to occupy Anne Thread.Sleep (1000); } catch (Interruptedexception e) {//TODO auto-generated catch block E.prin                    Tstacktrace ();                    } System.out.println ("T1 tried to occupy Anne"); System.out.println ("T1 waiting ....                    ");                    Synchronized (Annie) {System.out.println ("do something");    }            }            }        };        T1.start ();                    Thread t2 = new Thread () {public void run () {//Possession Anne synchronized (Annie) {                    System.out.println ("T2 already occupies Anne");                    try {//pause for 1000 seconds, another thread has enough time to occupy take up the nine Tail demon Fox thread.sleep (1000); } catch (Interruptedexception e) {//TODO auto-generated catch block E.pri                    Ntstacktrace ();                    } System.out.println ("T2 attempts to occupy Li Qing"); System.out.println ("T2 waiting ....                    ");                    Synchronized (leqing) {System.out.println ("do something");        }                }            }        };                T2.start (); Thread t3 = new Thread () {public void run () {synchronized (leqing) {System.                    Out.println ("T3 already occupies Li Qing");try {thread.sleep (1000);                    } catch (Interruptedexception e) {e.printstacktrace ();                    } System.out.println ("T3 tried to occupy nine tail fox"); System.out.println ("T3 waiting ....                ");                } synchronized (Ahri) {System.out.println ("do something");        }                            };        };    T3.start (); }}
The correct procedure is:
Package multiplethread;        public class Testthread {public static void main (string[] args) {Object A = new Object ();        Object B = new Object ();         Object c = new Object ();                        Thread T1 =new thread () {public void run () {synchronized (a) {try {                    Thread.Sleep (1000); } catch (Interruptedexception e) {//TODO auto-generated catch block E.prin                    Tstacktrace ();                                                     } synchronized (b) {synchronized (c) {        }                    }                }              }        };                        Thread T2 =new Thread () {public void run () {synchronized (c) {try {                    Thread.Sleep (1000); } catch (Interruptedexception e) {//TODO auto-generatedCatch block E.printstacktrace ();                                                     } synchronized (a) {synchronized (b) {        }                    }                }              }        };                        thread t3 =new thread () {public void run () {synchronized (b) {try {                    Thread.Sleep (1000); } catch (Interruptedexception e) {//TODO auto-generated catch block E.prin                    Tstacktrace ();                                                     } synchronized (c) {synchronized (a) {         }                    }                }              }        };        T1.start ();        T2.start ();           T3.start (); }         }

================

Using wait and notify for thread interaction

This.wait () means to let the thread occupying this wait, and temporarily release the possession
This.notify () indicates that the thread that waits on this is notified, and can come to an awakening.

public synchronized void recover() {        hp = hp + 1;         System.out.printf("%s 回血1点,增加血后,%s的血量是%.0f%n", name, name, hp);        // 通知那些等待在this对象上的线程,可以醒过来了,如第20行,等待着的减血线程,苏醒过来        this.notify();    }    // 掉血  同步方式和上面效果一样 这个方式    public void hurt() {        synchronized (this) {            if (hp == 1) {                // 让占有this的减血线程,暂时释放对this的占有,并等待                try {                    this.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            hp = hp - 1;            System.out.printf("%s 减血1点,减少血后,%s的血量是%.0f%n", name, name, hp);        }    }

Don't forget that the thread parent class is also an object

Topic-Thread Interaction

Assuming the blood thread runs more frequently, the hero's maximum blood volume is 1000.

To design the interaction between the blood thread and the blood-reducing thread, and then the blood thread waits until a blood-loss thread is lost after the blood-back is full.

    synchronized void Recover () {if (hp>=1000) {try {This.wai T ();            After addition of the} catch (Interruptedexception e) {e.printstacktrace ();        }} HP = hp + 1;        System.out.printf ("%s" Blood 1 points, increase blood, the volume of the%s is%.0f%n ", name, name, HP);     Notify those waiting on the This object thread, can wake up, such as line 73rd, waiting for the blood-reducing thread, Wake up this.notify ();                }//The blood-losing synchronization mode is the same as the above effect this way public void hurt () {synchronized (this) {if (HP = = 1) {                Let the bleed thread occupy this, temporarily release the possession of this, and wait for try {this.wait ();                } catch (Interruptedexception e) {e.printstacktrace ();            }} hp = Hp-1;                        System.out.printf ("%s" Minus 1 points, reduce blood, the blood volume of%s is%.0f%n ", name, name, HP);            Notify () means to notify a thread waiting on this synchronization object that you can wake up and have the opportunity to re-occupy the current object.   After losing the blood, wake up the Waiting Thread this.notify ();//After adding     }    } 
Topic-Multi-threaded interaction

On the basis of the above exercises, increase the health of the blood thread to 2, reduce the bleeding thread to 5 strips, and run at the same time.

Run for a period of time, observe the errors that occur, analyze the cause of the error, and consider the workaround

Topic-Producer Consumer issues

Producer-consumer issues are a very typical thread-interaction issue.

    1. Use stacks to store data
      1.1 Transform stacks to support thread safety
      1.2 The boundary operation of the stack is processed, and when the data in the stack is 0, the thread that accesses the pull waits. When the data in the stack is 200, the thread that accesses the push waits
    2. Provides a producer (Producer) thread class that produces random uppercase characters pressed into the stack
    3. Provides a consumer (Consumer) thread class that POPs characters off the stack and prints to the console
    4. Provides a test class that enables two producers and three consumer threads to run concurrently, with the results similar to the following:

==================

Lock

Topic

In the practice-thread-safe mystack exercise, use synchronized to modify the Mystack for thread-safe classes.

Next, modify the Mystack to a thread-safe class with lock

get rid of synchronized.
Use lock to occupy locks
Release the lock with unlock
Must be placed in the finally execution, in case Heros.addlast throws an exception will also be executed

Package multiplethread; Import Java.util.linkedlist;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.ReentrantLock; Import Charactor.    Hero;     public class Mystack {linkedlist
Topic-Solving deadlock problems with Trylock

Deadlocks can occur when multiple threads occupy multiple synchronization objects in different order.

Deadlock occurs because synchronized if the synchronization object is not occupied, it will be hard to wait, with the limited wait time of trylock, to solve the deadlock problem

Package multiplethread; Import Java.util.concurrent.timeunit;import Java.util.concurrent.locks.lock;import  Java.util.concurrent.locks.ReentrantLock; public class Testthread {public static void main (string[] args) throws Interruptedexception {Lock Lock_ahri        = new Reentrantlock ();          Lock Lock_annie = new Reentrantlock (); Thread t1 = new Thread () {public void run () {//Possession nine tail Demon Fox Boolean ahrilocked = Fal                Se                                  Boolean annielocked = false;                    try {ahrilocked = Lock_ahri.trylock (ten, timeunit.seconds);                        if (ahrilocked) {System.out.println ("T1 already occupies nine tails Fox");                        Pause for 1000 seconds, another thread has enough time to occupy Anne Thread.Sleep (1000);                        System.out.println ("T1 tried to occupy Anne within 10 seconds");        try {annielocked = Lock_annie.trylock (ten, timeunit.seconds);                    if (annielocked) System.out.println ("T1 succeeded to occupy Anne, began to Clap");                            else{System.out.println ("T1 always takes up Anne, give up"); }} finally {if (annielocked) {System.                                Out.println ("T1 release Anne");                            Lock_annie.unlock ();  }}}} catch (Interruptedexception E1) {//                TODO auto-generated Catch block E1.printstacktrace ();                        } finally {if (ahrilocked) {System.out.println ("T1 release nine-tailed fox");                    Lock_ahri.unlock ();        }                }              }        };                  T1.start ();                  Thread.Sleep (100); Thread t2 = new Thread () {public VOID Run () {Boolean annielocked = false;                                                  Boolean ahrilocked = false;                                  try {annielocked = Lock_annie.trylock (ten, timeunit.seconds);                        if (annielocked) {System.out.println ("T2 already occupies Anne");                        Pause for 1000 seconds, another thread has enough time to occupy Anne Thread.Sleep (1000);                        System.out.println ("T2 tried to occupy nine tail fox in 10 seconds");                            try {ahrilocked = Lock_ahri.trylock (ten, timeunit.seconds);                            if (ahrilocked) System.out.println ("T2 successfully occupy nine tail Fox, began to Pa");                            else{System.out.println ("T2 always can not occupy nine tail demon fox, give Up");                                }} finally {if (ahrilocked) { System.out.printlN ("T2 release nine-tailed fox");                            Lock_ahri.unlock (); }}}} catch (Interruptedexc                Eption E1) {//TODO auto-generated catch block E1.printstacktrace ();                        } finally {if (annielocked) {System.out.println ("T2 release Anne");                    Lock_annie.unlock ();        }                                          }            }        };          T2.start (); }}
Topic-Producer Consumer issues

In the practice-producer consumer problem This exercise is implemented with wait (), notify (), Notifyall.

Next use the Condition object: await, the Signal,signalall method achieves the same effect

Package multiplethread; Import Java.util.linkedlist;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.Lock; Import Java.util.concurrent.locks.ReentrantLock;     public class Mystack<t> {linkedlist<t> values = new linkedlist<t> ();    Lock lock = new Reentrantlock ();     Condition Condition = Lock.newcondition ();            public void push (T t) {try {lock.lock ();                while (Values.size () >=) {try {condition.await (); } catch (Interruptedexception e) {//TODO auto-generated catch block e.printstacktr                Ace ();            }} condition.signalall ();        Values.addlast (t);        } finally {Lock.unlock ();        }} public T-Pull () {T t=null;            try {lock.lock ();  while (Values.isempty ()) {try {condition.await ();              } catch (Interruptedexception e) {//TODO auto-generated catch block                E.printstacktrace ();            }} condition.signalall ();        T= Values.removelast ();        } finally {Lock.unlock ();    } return t;    } public T Peek () {return values.getlast (); }}
Title-use Atomicinteger to replace synchronized in the Hero class

Add modifiers to the Hero method synchronized this knowledge point by adding synchronized to hurt and recover methods to achieve a thread-safe effect.

This time replace the use of Atomicinteger to solve this problem

Tip: The int base type corresponds to Atomicinteger, but the float base type does not have a corresponding atomicfloat. So in this exercise, change HP to Atomicinteger.

java--Thread--Problem sets brocade

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.