Java multithreading and java threads
Synchronization and deadlock of threads:
Public class Child {public void say () {System. out. println ("give me a toy, I will give you a transcript! ");} Public void get () {System. out. println (" the child gets the toy! ");}}
Public class Father {public void say () {System. out. println ("give me a transcript, I'll give you a toy! ");} Public void get () {System. out. println (" my father got the transcript! ");}}
public class DeadTreadDemo implements Runnable { private static Father father = new Father(); private static Child child = new Child(); boolean flag = false; public void run(){ if(flag){ synchronized(father){ father.say(); try{ Thread.sleep(500); } catch(Exception e){ e.printStackTrace(); } synchronized(child){ father.get(); } } } else { synchronized(child){ child.say(); try{ Thread.sleep(500); } catch(Exception e){ e.printStackTrace(); } synchronized(father){ child.get(); } } } }}
public class TestDt { public static void main(String[] args) { DeadTreadDemo dd1 = new DeadTreadDemo(); DeadTreadDemo dd2 = new DeadTreadDemo(); dd1.flag = true; dd2.flag = false; new Thread(dd1).start(); new Thread(dd2).start(); }}
Genie thread:
Public class RunnableDemo implements Runnable {private String name; private int ticket = 5; public RunnableDemo (String name) {this. name = name;} // The genie thread public void run () {for (int I = 1; I <= 5; I ++) {synchronized (this) {if (ticket> 0) {try {Thread. sleep (1000);} catch (Exception e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "ticket selling:" + ticket --) ;}// System. out. println (Thread. currentThread (). getName () + "running:" + I) ;}} public static void main (String [] args) {RunnableDemo rd1 = new RunnableDemo ("aaa "); new Thread (rd1 ). start (); new Thread (rd1 ). start ();}}