java线程

来源:张孝祥老师

 

package cn.itcast.heima2;

public class TraditionalThread {

 /**
  * @param args
  */
 public static void main(String[] args) {
 
  Thread thread = new Thread(){
   @Override
   public void run() {
    while(true){
     try {
      Thread.sleep(500);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("1:" + Thread.currentThread().getName());
     System.out.println("2:" + this.getName());
    }
   }
  };
  thread.start();
  
  
  Thread thread2 = new Thread(new Runnable(){
   @Override
   public void run() {
    while(true){
     try {
      Thread.sleep(500);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("1:" + Thread.currentThread().getName());

    }    
    
   }
  });
  thread2.start();
  
  
  new Thread(
    new Runnable(){
     public void run() {
      while(true){
       try {
        Thread.sleep(500);
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
       System.out.println("runnable :" + Thread.currentThread().getName());

      }       
     }
    }
  ){
   public void run() {
    while(true){
     try {
      Thread.sleep(500);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("thread :" + Thread.currentThread().getName());

    } 
   }
  }.start();
  
  
 }

}
-----------------------------------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTimerTest {

 private static int count = 0;
 public static void main(String[] args) {
/*  new Timer().schedule(new TimerTask() {
   
   @Override
   public void run() {
    System.out.println("bombing!");
    
   }
  }, 10000,3000);*/
  

  class MyTimerTask extends TimerTask{
   
   @Override
   public void run() {
    count = (count+1)%2;
    System.out.println("bombing!");
    new Timer().schedule(/*new TimerTask() {
     
     @Override
     public void run() {
      System.out.println("bombing!");
     }
    }*/new MyTimerTask(),2000+2000*count);
   }
  }
  
  new Timer().schedule(new MyTimerTask(), 2000);
  
  while(true){
   System.out.println(new Date().getSeconds());
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

}

 

------------------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ThreadScopeShareData {

 private static int data = 0;
 private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();
 public static void main(String[] args) {
  for(int i=0;i<2;i++){
   new Thread(new Runnable(){
    @Override
    public void run() {
     int data = new Random().nextInt();
     System.out.println(Thread.currentThread().getName()
       + " has put data :" + data);
     threadData.put(Thread.currentThread(), data);
     new A().get();
     new B().get();
    }
   }).start();
  }
 }
 
 static class A{
  public void get(){
   int data = threadData.get(Thread.currentThread());
   System.out.println("A from " + Thread.currentThread().getName()
     + " get data :" + data);
  }
 }
 
 static class B{
  public void get(){
   int data = threadData.get(Thread.currentThread());   
   System.out.println("B from " + Thread.currentThread().getName()
     + " get data :" + data);
  }  
 }
}

 

-----------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

 

public class CallableAndFuture {

 /**
  * @param args
  */
 public static void main(String[] args) {
  ExecutorService threadPool =  Executors.newSingleThreadExecutor();
  Future<String> future =
   threadPool.submit(
    new Callable<String>() {
     public String call() throws Exception {
      Thread.sleep(2000);
      return "hello";
     };
    }
  );
  System.out.println("等待结果");
  try {
   System.out.println("拿到结果:" + future.get());
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  ExecutorService threadPool2 =  Executors.newFixedThreadPool(10);
  CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
  for(int i=1;i<=10;i++){
   final int seq = i;
   completionService.submit(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
     Thread.sleep(new Random().nextInt(5000));
     return seq;
    }
   });
  }
  for(int i=0;i<10;i++){
   try {
    System.out.println(
      completionService.take().get());
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 

}

 

---------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadPoolTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //ExecutorService threadPool = Executors.newFixedThreadPool(3);
  //ExecutorService threadPool = Executors.newCachedThreadPool();
  ExecutorService threadPool = Executors.newSingleThreadExecutor();
  for(int i=1;i<=10;i++){
   final int task = i;
   threadPool.execute(new Runnable(){
    @Override
    public void run() {
     for(int j=1;j<=10;j++){
      try {
       Thread.sleep(20);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for  task of " + task);
     }
    }
   });
  }
  System.out.println("all of 10 tasks have committed! ");
  //threadPool.shutdownNow();
  
  Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
    new Runnable(){
     @Override
    public void run() {
     System.out.println("bombing!");
     
    }},
    6,
    2,
    TimeUnit.SECONDS);
 }

}

------------------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ThreadLocalTest {

 private static ThreadLocal<Integer> x = new ThreadLocal<Integer>();
 private static ThreadLocal<MyThreadScopeData> myThreadScopeData = new ThreadLocal<MyThreadScopeData>();
 public static void main(String[] args) {
  for(int i=0;i<2;i++){
   new Thread(new Runnable(){
    @Override
    public void run() {
     int data = new Random().nextInt();
     System.out.println(Thread.currentThread().getName()
       + " has put data :" + data);
     x.set(data);
/*     MyThreadScopeData myData = new MyThreadScopeData();
     myData.setName("name" + data);
     myData.setAge(data);
     myThreadScopeData.set(myData);*/
     MyThreadScopeData.getThreadInstance().setName("name" + data);
     MyThreadScopeData.getThreadInstance().setAge(data);
     new A().get();
     new B().get();
    }
   }).start();
  }
 }
 
 static class A{
  public void get(){
   int data = x.get();
   System.out.println("A from " + Thread.currentThread().getName()
     + " get data :" + data);
/*   MyThreadScopeData myData = myThreadScopeData.get();;
   System.out.println("A from " + Thread.currentThread().getName()
     + " getMyData: " + myData.getName() + "," +
     myData.getAge());*/
   MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
   System.out.println("A from " + Thread.currentThread().getName()
     + " getMyData: " + myData.getName() + "," +
     myData.getAge());
  }
 }
 
 static class B{
  public void get(){
   int data = x.get();   
   System.out.println("B from " + Thread.currentThread().getName()
     + " get data :" + data);
   MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
   System.out.println("B from " + Thread.currentThread().getName()
     + " getMyData: " + myData.getName() + "," +
     myData.getAge());   
  }  
 }
}

class MyThreadScopeData{
 private MyThreadScopeData(){}
 public static /*synchronized*/ MyThreadScopeData getThreadInstance(){
  MyThreadScopeData instance = map.get();
  if(instance == null){
   instance = new MyThreadScopeData();
   map.set(instance);
  }
  return instance;
 }
 //private static MyThreadScopeData instance = null;//new MyThreadScopeData();
 private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();
 
 private String name;
 private int age;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}
----------------------------------------------------------------------

package cn.itcast.heima2;

public class MultiThreadShareData {

 private static ShareData1 data1 = new ShareData1();
 
 public static void main(String[] args) {
  ShareData1 data2 = new ShareData1();
  new Thread(new MyRunnable1(data2)).start();
  new Thread(new MyRunnable2(data2)).start();
  
  final ShareData1 data1 = new ShareData1();
  new Thread(new Runnable(){
   @Override
   public void run() {
    data1.decrement();
    
   }
  }).start();
  new Thread(new Runnable(){
   @Override
   public void run() {
    data1.increment();
    
   }
  }).start();

 }

}
 
 class MyRunnable1 implements Runnable{
  private ShareData1 data1;
  public MyRunnable1(ShareData1 data1){
   this.data1 = data1;
  }
  public void run() {
   data1.decrement();
   
  }
 }
 
 class MyRunnable2 implements Runnable{
  private ShareData1 data1;
  public MyRunnable2(ShareData1 data1){
   this.data1 = data1;
  }
  public void run() {
   data1.increment();
  }
 }

 class ShareData1 /*implements Runnable*/{
/*  private int count = 100;
  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(true){
    count--;
   }
  }*/
  
  
  private int j = 0;
  public synchronized void increment(){
   j++;
  }
  
  public synchronized void decrement(){
   j--;
  }
 }

 

-----------------------------------------------------------------------------------------

package cn.itcast.heima2;
public class User implements Cloneable{
 private String name;
 private int age;
 
 public User(String name, int age) {
  this.name = name;
  this.age = age;
 }
 public boolean equals(Object obj) {
  if(this == obj) {
   return true;
  }
  if(!(obj instanceof User)) {
   return false; 
  }
  User user = (User)obj;
  //if(this.name==user.name && this.age==user.age)
  if(this.name.equals(user.name)
   && this.age==user.age) {
   return true;
  }
  else {
   return false;
  }
 }
 public int hashCode() {
  return name.hashCode() + age;
 }
 
 public String toString() {
  return "{name:'" + name + "',age:" + age + "}";
 }
 public Object clone()  {
  Object object = null;
  try {
   object = super.clone();
  } catch (CloneNotSupportedException e) {}
  return object;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
}
------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
 public static void main(String[] args) {
  ExecutorService service = Executors.newCachedThreadPool();
  final  Semaphore sp = new Semaphore(3);
  for(int i=0;i<10;i++){
   Runnable runnable = new Runnable(){
     public void run(){
     try {
      sp.acquire();
     } catch (InterruptedException e1) {
      e1.printStackTrace();
     }
     System.out.println("线程" + Thread.currentThread().getName() +
       "进入,当前已有" + (3-sp.availablePermits()) + "个并发");
     try {
      Thread.sleep((long)(Math.random()*10000));
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("线程" + Thread.currentThread().getName() +
       "即将离开");     
     sp.release();
     //下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元
     System.out.println("线程" + Thread.currentThread().getName() +
       "已离开,当前已有" + (3-sp.availablePermits()) + "个并发");     
    }
   };
   service.execute(runnable);   
  }
 }

}
-----------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTest {
 public static void main(String[] args) {
  final Queue3 q3 = new Queue3();
  for(int i=0;i<3;i++)
  {
   new Thread(){
    public void run(){
     while(true){
      q3.get();      
     }
    }
    
   }.start();

   new Thread(){
    public void run(){
     while(true){
      q3.put(new Random().nextInt(10000));
     }
    }   
    
   }.start();
  }
  
 }
}

class Queue3{
 private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
 ReadWriteLock rwl = new ReentrantReadWriteLock();
 public void get(){
  rwl.readLock().lock();
  try {
   System.out.println(Thread.currentThread().getName() + " be ready to read data!");
   Thread.sleep((long)(Math.random()*1000));
   System.out.println(Thread.currentThread().getName() + "have read data :" + data);   
  } catch (InterruptedException e) {
   e.printStackTrace();
  }finally{
   rwl.readLock().unlock();
  }
 }
 
 public void put(Object data){

  rwl.writeLock().lock();
  try {
   System.out.println(Thread.currentThread().getName() + " be ready to write data!");     
   Thread.sleep((long)(Math.random()*1000));
   this.data = data;  
   System.out.println(Thread.currentThread().getName() + " have write data: " + data);     
  } catch (InterruptedException e) {
   e.printStackTrace();
  }finally{
   rwl.writeLock().unlock();
  }
  
 
 }
}
---------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class LockTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  new LockTest().init();
 }
 
 private void init(){
  final Outputer outputer = new Outputer();
  new Thread(new Runnable(){
   @Override
   public void run() {
    while(true){
     try {
      Thread.sleep(10);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     outputer.output("zhangxiaoxiang");
    }
    
   }
  }).start();
  
  new Thread(new Runnable(){
   @Override
   public void run() {
    while(true){
     try {
      Thread.sleep(10);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     outputer.output("lihuoming");
    }
    
   }
  }).start();
  
 }

 static class Outputer{
  Lock lock = new ReentrantLock();
  public void output(String name){
   int len = name.length();
   lock.lock();
   try{
    for(int i=0;i<len;i++){
     System.out.print(name.charAt(i));
    }
    System.out.println();
   }finally{
    lock.unlock();
   }
  }
  
  public synchronized void output2(String name){
   int len = name.length();
   for(int i=0;i<len;i++){
     System.out.print(name.charAt(i));
   }
   System.out.println();
  }
  
  public static synchronized void output3(String name){
   int len = name.length();
   for(int i=0;i<len;i++){
     System.out.print(name.charAt(i));
   }
   System.out.println();
  } 
 }
}
---------------------------------------------------------------------------------

package cn.itcast.heima2;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerTest {

 public static void main(String[] args) {
  ExecutorService service = Executors.newCachedThreadPool();
  final Exchanger exchanger = new Exchanger();
  service.execute(new Runnable(){
   public void run() {
    try {    

     String data1 = "zxx";
     System.out.println("线程" + Thread.currentThread().getName() +
     "正在把数据" + data1 +"换出去");
     Thread.sleep((long)(Math.random()*10000));
     String data2 = (String)exchanger.exchange(data1);
     System.out.println("线程" + Thread.currentThread().getName() +
     "换回的数据为" + data2);
    }catch(Exception e){
     
    }
   } 
  });
  service.execute(new Runnable(){
   public void run() {
    try {    

     String data1 = "lhm";
     System.out.println("线程" + Thread.currentThread().getName() +
     "正在把数据" + data1 +"换出去");
     Thread.sleep((long)(Math.random()*10000));     
     String data2 = (String)exchanger.exchange(data1);
     System.out.println("线程" + Thread.currentThread().getName() +
     "换回的数据为" + data2);
    }catch(Exception e){
     
    }    
   } 
  });  
 }
}
-----------------------------------------------------------------------------------------

package cn.itcast.heima2;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {

 public static void main(String[] args) {
  ExecutorService service = Executors.newCachedThreadPool();
  final  CyclicBarrier cb = new CyclicBarrier(3);
  for(int i=0;i<3;i++){
   Runnable runnable = new Runnable(){
     public void run(){
     try {
      Thread.sleep((long)(Math.random()*10000)); 
      System.out.println("线程" + Thread.currentThread().getName() +
        "即将到达集合地点1,当前已有" + (cb.getNumberWaiting()+1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候"));      
      cb.await();
      
      Thread.sleep((long)(Math.random()*10000)); 
      System.out.println("线程" + Thread.currentThread().getName() +
        "即将到达集合地点2,当前已有" + (cb.getNumberWaiting()+1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候"));
      cb.await(); 
      Thread.sleep((long)(Math.random()*10000)); 
      System.out.println("线程" + Thread.currentThread().getName() +
        "即将到达集合地点3,当前已有" + (cb.getNumberWaiting() + 1) + "个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候"));      
      cb.await();      
     } catch (Exception e) {
      e.printStackTrace();
     }    
    }
   };
   service.execute(runnable);
  }
  service.shutdown();
 }
}
------------------------------------------------------------------------------------

package cn.itcast.heima2;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountdownLatchTest {

 public static void main(String[] args) {
  ExecutorService service = Executors.newCachedThreadPool();
  final CountDownLatch cdOrder = new CountDownLatch(1);
  final CountDownLatch cdAnswer = new CountDownLatch(3);  
  for(int i=0;i<3;i++){
   Runnable runnable = new Runnable(){
     public void run(){
     try {
      System.out.println("线程" + Thread.currentThread().getName() +
        "正准备接受命令");      
      cdOrder.await();
      System.out.println("线程" + Thread.currentThread().getName() +
      "已接受命令");        
      Thread.sleep((long)(Math.random()*10000)); 
      System.out.println("线程" + Thread.currentThread().getName() +
        "回应命令处理结果");      
      cdAnswer.countDown();      
     } catch (Exception e) {
      e.printStackTrace();
     }    
    }
   };
   service.execute(runnable);
  }  
  try {
   Thread.sleep((long)(Math.random()*10000));
  
   System.out.println("线程" + Thread.currentThread().getName() +
     "即将发布命令");      
   cdOrder.countDown();
   System.out.println("线程" + Thread.currentThread().getName() +
   "已发送命令,正在等待结果"); 
   cdAnswer.await();
   System.out.println("线程" + Thread.currentThread().getName() +
   "已收到所有响应结果"); 
  } catch (Exception e) {
   e.printStackTrace();
  }    
  service.shutdown();

 }
}
---------------------------------------------------------------------------

package cn.itcast.heima2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class CollectionModifyExceptionTest {
 public static void main(String[] args) {
  Collection users = new CopyOnWriteArrayList();
   
   //new ArrayList();
  users.add(new User("张三",28)); 
  users.add(new User("李四",25));   
  users.add(new User("王五",31)); 
  Iterator itrUsers = users.iterator();
  while(itrUsers.hasNext()){
   System.out.println("aaaa");
   User user = (User)itrUsers.next();
   if("李四".equals(user.getName())){
    users.remove(user);
    //itrUsers.remove();
   } else {
    System.out.println(user);    
   }
  }
 }

--------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheDemo {

 private Map<String, Object> cache = new HashMap<String, Object>();
 public static void main(String[] args) {
  // TODO Auto-generated method stub

 }

 private ReadWriteLock rwl = new ReentrantReadWriteLock();
 public  Object getData(String key){
  rwl.readLock().lock();
  Object value = null;
  try{
   value = cache.get(key);
   if(value == null){
    rwl.readLock().unlock();
    rwl.writeLock().lock();
    try{
     if(value==null){
      value = "aaaa";//实际失去queryDB();
     }
    }finally{
     rwl.writeLock().unlock();
    }
    rwl.readLock().lock();
   }
  }finally{
   rwl.readLock().unlock();
  }
  return value;
 }
}
-------------------------------------------------------------------------

package cn.itcast.heima2;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueTest {
 public static void main(String[] args) {
  final BlockingQueue queue = new ArrayBlockingQueue(3);
  for(int i=0;i<2;i++){
   new Thread(){
    public void run(){
     while(true){
      try {
       Thread.sleep((long)(Math.random()*1000));
       System.out.println(Thread.currentThread().getName() + "准备放数据!");       
       queue.put(1);
       System.out.println(Thread.currentThread().getName() + "已经放了数据," +        
          "队列目前有" + queue.size() + "个数据");
      } catch (InterruptedException e) {
       e.printStackTrace();
      }

     }
    }
    
   }.start();
  }
  
  new Thread(){
   public void run(){
    while(true){
     try {
      //将此处的睡眠时间分别改为100和1000,观察运行结果
      Thread.sleep(1000);
      System.out.println(Thread.currentThread().getName() + "准备取数据!");
      queue.take();
      System.out.println(Thread.currentThread().getName() + "已经取走数据," +        
        "队列目前有" + queue.size() + "个数据");     
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
   
  }.start();   
 }
}
------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class BlockingQueueCommunication {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  final Business business = new Business();
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       business.sub(i);
      }
      
     }
    }
  ).start();
  
  for(int i=1;i<=50;i++){
   business.main(i);
  }
  
 }

  static class Business {
  
  
    BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
    BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
   
    {
     Collections.synchronizedMap(null);
     try {
      System.out.println("xxxxxdfsdsafdsa");
    queue2.put(1);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
    }
   
    public  void sub(int i){
      try {
     queue1.put(1);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    for(int j=1;j<=10;j++){
     System.out.println("sub thread sequece of " + j + ",loop of " + i);
    }
    try {
     queue2.take();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    }
   
    public  void main(int i){
      try {
     queue2.put(1);
    } catch (InterruptedException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    }
    for(int j=1;j<=100;j++){
     System.out.println("main thread sequece of " + j + ",loop of " + i);
    }
    try {
     queue1.take();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    }
   }

}
--------------------------------------------------------------------------------------

package cn.itcast.heima2;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionCommunication {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  final Business business = new Business();
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       business.sub(i);
      }
      
     }
    }
  ).start();
  
  for(int i=1;i<=50;i++){
   business.main(i);
  }
  
 }

 static class Business {
   Lock lock = new ReentrantLock();
   Condition condition = lock.newCondition();
    private boolean bShouldSub = true;
    public  void sub(int i){
     lock.lock();
     try{
      while(!bShouldSub){
       try {
      condition.await();
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
      }
     for(int j=1;j<=10;j++){
      System.out.println("sub thread sequence of " + j + ",loop of " + i);
     }
      bShouldSub = false;
      condition.signal();
     }finally{
      lock.unlock();
     }
    }
   
    public  void main(int i){
     lock.lock();
     try{
     while(bShouldSub){
        try {
       condition.await();
      } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
       }
     for(int j=1;j<=100;j++){
      System.out.println("main thread sequence of " + j + ",loop of " + i);
     }
     bShouldSub = true;
     condition.signal();
    }finally{
     lock.unlock();
    }
   }
 
 }
}
------------------------------------------------------------------------

package cn.itcast.heima2;

public class TraditionalThreadSynchronized {

 /**
  * @param args
  */
 public static void main(String[] args) {
  new TraditionalThreadSynchronized().init();
 }
 
 private void init(){
  final Outputer outputer = new Outputer();
  new Thread(new Runnable(){
   @Override
   public void run() {
    while(true){
     try {
      Thread.sleep(10);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     outputer.output("zhangxiaoxiang");
    }
    
   }
  }).start();
  
  new Thread(new Runnable(){
   @Override
   public void run() {
    while(true){
     try {
      Thread.sleep(10);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     outputer.output3("lihuoming");
    }
    
   }
  }).start();
  
 }

 static class Outputer{
  
  public void output(String name){
   int len = name.length();
   synchronized (Outputer.class)
   {
    for(int i=0;i<len;i++){
     System.out.print(name.charAt(i));
    }
    System.out.println();
   }
  }
  
  public synchronized void output2(String name){
   int len = name.length();
   for(int i=0;i<len;i++){
     System.out.print(name.charAt(i));
   }
   System.out.println();
  }
  
  public static synchronized void output3(String name){
   int len = name.length();
   for(int i=0;i<len;i++){
     System.out.print(name.charAt(i));
   }
   System.out.println();
  } 
 }
}
----------------------------------------------------------------

package cn.itcast.heima2;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreeConditionCommunication {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  final Business business = new Business();
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       business.sub2(i);
      }
      
     }
    }
  ).start();
  
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       business.sub3(i);
      }
      
     }
    }
  ).start();  
  
  for(int i=1;i<=50;i++){
   business.main(i);
  }
  
 }

 static class Business {
   Lock lock = new ReentrantLock();
   Condition condition1 = lock.newCondition();
   Condition condition2 = lock.newCondition();
   Condition condition3 = lock.newCondition();
    private int shouldSub = 1;
    public  void sub2(int i){
     lock.lock();
     try{
      while(shouldSub != 2){
       try {
      condition2.await();
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
      }
     for(int j=1;j<=10;j++){
      System.out.println("sub2 thread sequence of " + j + ",loop of " + i);
     }
      shouldSub = 3;
      condition3.signal();
     }finally{
      lock.unlock();
     }
    }

    public  void sub3(int i){
     lock.lock();
     try{
      while(shouldSub != 3){
       try {
      condition3.await();
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
      }
     for(int j=1;j<=20;j++){
      System.out.println("sub3 thread sequence of " + j + ",loop of " + i);
     }
      shouldSub = 1;
      condition1.signal();
     }finally{
      lock.unlock();
     }
    }   
   
    public  void main(int i){
     lock.lock();
     try{
     while(shouldSub != 1){
        try {
       condition1.await();
      } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
       }
     for(int j=1;j<=100;j++){
      System.out.println("main thread sequence of " + j + ",loop of " + i);
     }
     shouldSub = 2;
     condition2.signal();
    }finally{
     lock.unlock();
    }
   }
 
 }
}
--------------------------------------------------------------

package cn.itcast.heima2;

import java.util.concurrent.atomic.AtomicInteger;

public class TraditionalThreadCommunication {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  final Business business = new Business();
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       business.sub(i);
      }
      
     }
    }
  ).start();
  
  for(int i=1;i<=50;i++){
   business.main(i);
  }
  
 }

}
  class Business {
   private boolean bShouldSub = true;
   public synchronized void sub(int i){
    while(!bShouldSub){
     try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
    }
   for(int j=1;j<=10;j++){
    System.out.println("sub thread sequence of " + j + ",loop of " + i);
   }
    bShouldSub = false;
    this.notify();
   }
  
   public synchronized void main(int i){
     while(bShouldSub){
      try {
     this.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
     }
   for(int j=1;j<=100;j++){
    System.out.println("main thread sequence of " + j + ",loop of " + i);
   }
   bShouldSub = true;
   this.notify();
   }
  }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值