java多线程基础

多线程基础

读书练习照猫画虎

  1 package Threadtest;
  2 
  3 import java.util.Date;
  4 import java.util.concurrent.ArrayBlockingQueue;
  5 import java.util.concurrent.BlockingQueue;
  6 import java.util.concurrent.locks.Condition;
  7 import java.util.concurrent.locks.Lock;
  8 import java.util.concurrent.locks.ReentrantLock;
  9 
 10 public class ThreadExerc {
 11     public static void main(String[] args) throws Exception{
 12         /*
 13          * join
 14          */
 15 //        new JoinThread("new thread").start();
 16 //        for(int i=0; i<100; i++){
 17 //            if(i==20){
 18 //                JoinThread jt = new JoinThread("Joined Thread");
 19 //                jt.start();
 20 //                jt.join();
 21 //            }
 22 //            System.out.println(Thread.currentThread().getName()+"--"+i);
 23 //        }
 24         /*
 25          * sleep
 26          */
 27         //testSleep();
 28         
 29         /*
 30          * yeild
 31          */
 32         //testYeild();
 33         
 34         /*
 35          * 传统线程间通信
 36          */
 37 //        Account ac = new Account("123456", 0);
 38 //        new DrawThread("取钱者甲", ac, 1000).start();
 39 //        new DrawThread("取钱者乙", ac, 1000).start();
 40 //        new DrawThread("取钱者丙", ac, 1000).start();
 41 //        new DepositThread("存钱者A", ac, 1000).start();
 42 //        new DepositThread("存钱者B", ac, 1000).start();
 43 //        new DepositThread("存钱者C", ac, 1000).start();
 44 //        
 45         /*
 46          * 阻塞队列线程间通信---ArrayBlockingQueue
 47          */
 48         BlockingQueue<String> bq = new ArrayBlockingQueue<>(5);
 49         new Producer("工厂A", bq).start();
 50         new Producer("工厂B",bq).start();
 51         new Producer("工厂C",bq).start();
 52         new Consumer("客户A",bq).start();
 53         new Consumer("客户B",bq).start();
 54     }
 55     static void testSleep() throws Exception{
 56     int i = 1;
 57     while(i++<100){
 58         System.out.println("Current Time is : "+ new Date());
 59         Thread.sleep(10000);
 60     }
 61     
 62     
 63     }
 64     static void testYeild() {
 65         class TestY extends Thread{
 66             public TestY(String name){
 67                 super(name);
 68             }
 69             public void run(){
 70                 for(int i=0; i<100; i++){
 71                     System.out.println(getName() + "--" + i);
 72                     if(i==20) Thread.yield();
 73                 }
 74             }
 75         }
 76         TestY t1 = new TestY("higher one");
 77         TestY t2 = new TestY("lowwer one");
 78 //        t1.setPriority(Thread.MAX_PRIORITY);
 79 //        t2.setPriority(Thread.MIN_PRIORITY);
 80         t1.start();
 81         t2.start();
 82         
 83     }
 84 }
 85 
 86 
 87 
 88 
 89 class JoinThread extends Thread{
 90     public JoinThread(String name){
 91         super(name);
 92     }
 93     public void run(){
 94         for(int i=0; i<100; i++){
 95             System.out.println(getName()+"--"+i);
 96         }
 97     }
 98 }
 99 
100 class Account{
101     private String accountNo;
102     private double ballance;
103     private boolean flag = false;
104     private final Lock lock = new ReentrantLock();
105     private final Condition cond = lock.newCondition();
106     public Account(String accountNo, double ballance) {
107         super();
108         this.accountNo = accountNo;
109         this.ballance = ballance;
110     }
111     public String getAccountNo() {
112         return accountNo;
113     }
114     public void setAccountNo(String accountNo) {
115         this.accountNo = accountNo;
116     }
117     public double getBallance() {
118         return ballance;
119     }
120 //    public synchronized void draw(double drawAmount){
121     public void draw(double drawAmount){
122         lock.lock();
123         try{
124             if(!flag ){
125                 //wait();
126                 cond.await();
127             }else{
128                 System.out.println(Thread.currentThread().getName()+" 取钱: "+drawAmount);
129                 ballance -= drawAmount;
130                 System.out.println("余额:"+ballance);
131                 flag = !flag;
132                 //notifyAll();
133                 cond.signalAll();
134             }
135         }catch(Exception e){
136             e.printStackTrace();
137         }finally{
138             lock.unlock();
139         }
140     }
141 //    public synchronized void deposit(double depositAmount){
142     public void deposit(double depositAmount){    
143         lock.lock();
144         try{
145             if(flag){
146 //                wait();
147                 cond.await();
148             }else{
149                 System.out.println(Thread.currentThread().getName()+" 存钱: "+depositAmount);
150                 ballance += depositAmount;
151                 System.out.println("余额:"+ballance);
152                 flag = !flag;
153 //                notifyAll();
154                 cond.signalAll();
155             }
156         }catch(Exception e){
157             e.printStackTrace();
158         }finally{
159             lock.unlock();
160         }
161     }
162     
163 }
164 class DrawThread extends Thread{
165     private Account ac;
166     private double drawAmount;
167     public DrawThread(String name , Account ac, double drawAmount){
168         super(name);
169         this.ac = ac;
170         this.drawAmount = drawAmount;
171     }
172     public void run(){
173         for(int i=0; i<100; i++){
174             ac.draw(drawAmount);
175             System.out.println(super.getName()+","+i);
176         }
177     }
178 }
179 class DepositThread extends Thread{
180     private Account ac;
181     private double depositAmount;
182     public DepositThread(String name , Account ac, double depositAmount){
183         super(name);
184         this.ac = ac;
185         this.depositAmount = depositAmount;
186     }
187     public void run(){
188         for(int i=0; i<100; i++){
189             ac.deposit(depositAmount);
190             System.out.println(super.getName()+","+i);
191         }
192     }
193 }
194 
195 //================================
196 class Producer extends Thread{
197     private BlockingQueue<String> bq;
198 
199     public Producer(String name, BlockingQueue<String> bq) {
200         super(name);
201         this.bq = bq;
202     }
203     public void run(){
204         String[] strArr = new String[]{
205                 "java",
206                 "Spring",
207                 "struts",
208                 "batis"
209         };
210         for(int i=0; i<1000; i++){
211             System.out.println(getName()+"生产者准备生产集合元素!");
212             try {
213                 Thread.sleep(200);
214                 bq.put(strArr[i%4]);
215             } catch (InterruptedException e) {
216                 // TODO Auto-generated catch block
217                 e.printStackTrace();
218             }
219             System.out.println(getName()+"生产者完成!"+bq);
220         }
221     }
222 }
223 class Consumer extends Thread{
224     private BlockingQueue<String> bq;
225 
226     public Consumer(String name, BlockingQueue<String> bq) {
227         super(name);
228         this.bq = bq;
229     }
230     public void run(){
231         while(true){
232             System.out.println(getName()+"消费者准备消费集合元素!");
233             try {
234                 Thread.sleep(200);
235                 bq.take();
236             } catch (InterruptedException e) {
237                 // TODO Auto-generated catch block
238                 e.printStackTrace();
239             }
240             System.out.println(getName()+"消费者完成!"+bq);
241         }
242     }
243 }
原文地址:https://www.cnblogs.com/steve-jiang/p/6078056.html