This is an example from the Java programming mindset
[Java]View Plaincopy
- Package demo.thread;
- /**
- *sleep () is a static method that belongs to a class that is used to block the current thread
- *join () is a thread that synchronizes threads, such as calling T.join () in a thread to indicate that the T thread executes and then executes the current thread
- *interrupt () sets a flag to a thread indicating that the thread has been interrupted, but this flag will be cleaned up when the exception is captured
- * So in the catch clause, the flag is false
- */
- Public class Sleepjoindemo {
- public static void Main (string[] args) {
- Sleeper sleep1 = new Sleeper ("Sleep1", 1500);
- Sleeper SLEEP2 = new Sleeper ("SLEEP2", 1500);
- Joiner join1 = new Joiner ("Join1", SLEEP1);
- Joiner join2 = new Joiner ("join2", SLEEP1);
- Sleep2.interrupt ();
- }
- }
- Class Sleeper extends Thread {
- //can set the sleep time by the parameter
- private int sleeptime;
- Public Sleeper (String name, int sleeptime) {
- super (name);
- this.sleeptime = sleeptime;
- Start (); //Start in construction method
- }
- @Override
- public Void Run () {
- try {
- Sleep (Sleeptime);
- } catch (Interruptedexception e) {
- System.out.println (GetName () + "was interrupted.\n"
- + "isinterrupted ():" + isinterrupted ());
- return;
- }
- System.out.println (GetName () + "has awakened");
- }
- }
- Class Joiner extends Thread {
- private Sleeper Sleeper;
- Public Joiner (String name, Sleeper Sleeper) {
- super (name);
- this.sleeper = sleeper;
- Start ();
- }
- public Void Run () {
- try {
- Sleeper.join (); //merge, asynchronous Sync
- } catch (Interruptedexception e) {
- System.out.println ("interrupted");
- }
- System.out.println (GetName () + "join completed");
- }
- }
Java Multithreading summary Three: Sleep (), join (), interrupt () example