zoukankan      html  css  js  c++  java
  • 多线程的使用

     一.继承Thread类创建线程

     1 package com.thread1;
     2 /**
     3  * 1.继承Thread类创建线程
     4  */
     5 public class ThreadTest extends Thread{
     6     private int count=0;
     7     /**
     8      * 线程执行任务的方法
     9      */
    10     @Override
    11     public void run() {
    12         while(count<100){
    13             count++;
    14             System.out.println("count的值是:"+count);
    15         }
    16     }
    17     /**
    18      * 主线程的入口
    19      */
    20     public static void main(String[] args) {
    21         //创建线程对象
    22         ThreadTest tt=new ThreadTest();
    23         
    24         //启动线程(其实调用线程对象里的run方法)
    25         tt.start();
    26     }
    27 
    28 }
    ThreadTest.java

    二..实现Runnable接口创建线程

     1 package com.rannable;
     2 /**
     3  * 2.实现Runnable接口创建线程
     4  * @author Administrator
     5  *
     6  */
     7 public class RunnableTest implements Runnable{
     8     private int count=0;
     9     /**
    10      * 执行线程任务
    11      */
    12     @Override
    13     public void run() {
    14         while(count<100){
    15             count++;
    16         }
    17         System.out.println("count的值:"+count);
    18         
    19     }
    20     
    21     /**
    22      *主线程
    23      */
    24     public static void main(String[] args) {
    25         //通过创建线程对象
    26         RunnableTest rt=new RunnableTest();
    27         
    28         Thread t=new Thread(rt);
    29         //启动线程
    30         t.start();
    31         Thread t2=new Thread(rt);
    32         //启动线程
    33         t2.start();
    34         Thread t3=new Thread(rt);
    35         //启动线程
    36         t3.start();
    37         Thread t4=new Thread(rt);
    38         //启动线程
    39         t4.start();
    40 
    41     }
    42 
    43 
    44 }
    RunnableTest.java

    三.join线程插队

     1 package com.join;
     2 /**
     3  * 3.使用join时对给变量赋值的影响
     4  *
     5  */
     6 public class JoinSetFieldTest extends Thread{
     7     public String val1;
     8     public String val2;
     9     /**线程执行任务的方法*/
    10     public void run(){
    11         val1="456";
    12         val2="123";
    13     }
    14     
    15 
    16     /**主线程入口
    17      * @throws InterruptedException */
    18     public static void main(String[] args) throws InterruptedException {
    19         //线程对象实例化
    20         JoinSetFieldTest jsft =new JoinSetFieldTest();
    21         
    22         //启动线程
    23         jsft.start();
    24         
    25         //表示先让上面的线程执行完毕,再次执行当前线程:大脑没停,动作停了
    26         //jsft.join();
    27         System.out.println("val1:"+jsft.val1);
    28         System.out.println("val2:"+jsft.val2);
    29 
    30     }
    31 
    32 }
    JoinSetFieldTest.java
     1 package com.join;
     2 
     3 /**
     4  * 3.使用join方法暂停执行当前线程,等待调用该方法的线程结束之后再继续执行本线程
     5  */
     6 public class JoinTest extends Thread {
     7     // 获取线程的名字
     8     public JoinTest(String name) {
     9         super(name);
    10     }
    11     /**
    12      * 线程任务执行的方法
    13      */
    14     public void run() {
    15         for (int i = 1; i <= 5; i++) {
    16             // 输出当前线程的名字
    17             System.out.println(Thread.currentThread().getName() + "" + i);
    18         }
    19     }
    20 
    21     /**
    22      * 主线程入口
    23      * 
    24      * @param args
    25      * @throws InterruptedException
    26      */
    27     public static void main(String[] args) throws InterruptedException {
    28 
    29         for (int i = 1; i <= 10; i++) {
    30             if (i == 5) {
    31                 JoinTest jt = new JoinTest("JoinTest");
    32                 jt.start();
    33                 //把该线程通过join方法,插入到下面主线程的前面,也就是执行该线程
    34                 //暂停将主线程阻塞状态,等待该线程执行完,再执行主线程
    35                 jt.join();
    36             }
    37             System.out.println(Thread.currentThread().getName() + "" + i);
    38         }
    39     }
    40 
    41 }
    JoinTest.java

    四.sleep线程休眠

    package com.sleep;
    /**
     * 5.线程休眠
     * @author Administrator
     *
     */
    public class SleepTest extends Thread{
        
        public static void se() throws InterruptedException{
            /**
             * 线程每次睡眠1秒
             */
            for (int i = 1; i <= 5; i++) {
                System.out.println(i+"秒");
                //线程睡眠1秒
                Thread.sleep(1000);//睡眠状态:大脑和动作处于不可运转状态,阻塞状态
            }
        }
    
        /** 主线程入口
         * @throws InterruptedException */
        public static void main(String[] args) throws InterruptedException {
                 System.out.println("等待");
                 
                 //让主线程等待5秒后再次执行
                 SleepTest.se();
                 
                 System.out.println("start");
        }
    
    }
    SleepTest.java

    五.同步代码块/代码块

    1.创建银行账户表

     1 package cn.com.jbit;
     2 
     3 //银行帐户类
     4 public class Account {
     5  private int balance = 500; //余额
     6  public int getBalance() {
     7     return balance;
     8  }
     9  //取款
    10  public void withdraw(int amount) {
    11     balance = balance - amount;
    12  }
    13 }
    Account .java

    2.取款线程类

     1 package cn.com.jbit;
     2 
     3 //取款的线程类
     4 public class TestAccount implements Runnable {
     5     // 所有用TestAccount对象创建的线程共享同一个帐户对象
     6     private Account acct = new Account();
     7 
     8     public void run() {
     9         for (int i = 0; i < 5; i++) {
    10             makeWithdrawal(100);// 取款
    11             if (acct.getBalance() < 0) {
    12                 System.out.println("账户透支了!");
    13             }
    14         }
    15     }
    16 
    17     private void makeWithdrawal(int amt) {
    18         synchronized (acct) {
    19             if (acct.getBalance() >= amt) {
    20                 System.out.println(Thread.currentThread().getName() + " 准备取款");
    21                 try {
    22                     Thread.sleep(500);// 0.5秒后实现取款
    23                 } catch (InterruptedException ex) {
    24                 }
    25                 // 如果余额足够,则取款
    26                 acct.withdraw(amt);
    27                 System.out.println(Thread.currentThread().getName() + " 完成取款");
    28             } else {
    29                 // 余额不足给出提示
    30                 System.out.println("余额不足以支付 "
    31                         + Thread.currentThread().getName() + " 的取款,余额为 "
    32                         + acct.getBalance());
    33             }
    34         }
    35     }
    36 }
    TestAccount.java

    3.测试类

     1 package cn.com.jbit;
     2 //测试类
     3 public class TestWithdrawal {
     4  public static void main (String [] args) {
     5      //创建两个线程
     6        TestAccount r = new TestAccount();
     7      Thread one = new Thread(r);
     8      Thread two = new Thread(r);
     9      one.setName("张三");
    10      two.setName("张三的妻子");
    11      //启动线程
    12      one.start();
    13      two.start();
    14  }
    15 }
    TestWithdrawal.java

    六、线程间通信

    案例1:

     1 package cn.com.jbit;
     2 //测试线程间通信
     3 public class CommunicateThread implements Runnable{
     4     public static void main(String[] args) {
     5         CommunicateThread thread=new CommunicateThread();
     6         Thread ta=new Thread(thread,"线程ta");
     7         Thread tb=new Thread(thread,"线程tb");
     8         ta.start();
     9         tb.start();
    10     }
    11   //同步run()方法
    12     synchronized public void run() {
    13         for(int i=0;i<5;i++){
    14             System.out.println(Thread.currentThread().getName()+i);
    15             if(i==2){
    16                 try {                
    17                     wait();//退出运行态,放弃资源锁,进入到等待队列
    18                 } catch (InterruptedException e) {
    19                     e.printStackTrace();
    20                 }
    21             }
    22             if(i==1){                               
    23                 notify(); //从等待序列中唤起一个线程
    24             }
    25             if(i==4){
    26                 notify();
    27             }
    28         }
    29     }
    30 }
    CommunicateThread.java

    案例2:

    1.采购类

     1 package com.thread.customer;
     2 
     3 public class Purchase {
     4     private int count;
     5 
     6     public synchronized void completes(int count){
     7         if(count==0){
     8             System.out.println("库存不够,请等待采购入库....");
     9             try {
    10                 wait();
    11             } catch (InterruptedException e) {
    12                 // TODO Auto-generated catch block
    13                 e.printStackTrace();
    14             }
    15         }
    16         count=count;
    17         notify();        //通知顾客可以购买了
    18     }
    19     public synchronized void getGoods(int count){
    20         if(count==0){
    21             System.out.println("采购还未入库,顾客停止购买");
    22             try {
    23                 wait();
    24             } catch (InterruptedException e) {
    25                 // TODO Auto-generated catch block
    26                 e.printStackTrace();
    27             }
    28         }
    29         count=count;
    30         notify();
    31         System.out.println("采购入库完成,请继续购买。。。。。。");
    32 
    33     } 
    34 }
    Purchase.java

    2.采购线程类

     1 package com.thread.customer;
     2 
     3 public class PurchaseThead extends Thread{
     4     private Purchase p;
     5     public PurchaseThead(Purchase p){
     6         this.p=p;
     7     }
     8     public void run(){
     9         int count=0;
    10         do{
    11             try {
    12                 Thread.sleep((int)(Math.random()*3000));
    13             } catch (InterruptedException e) {
    14                 // TODO Auto-generated catch block
    15                 e.printStackTrace();
    16             }
    17             p.getGoods(count);
    18             count++;
    19         }while(count<10);
    20     }
    21 }
    PurchaseThead.java

    3.顾客类

     1 package com.thread.customer;
     2 
     3 public class CustomerThread extends Thread {
     4     private Purchase p;
     5     public CustomerThread(Purchase p){
     6         this.p=p;
     7     }
     8     public void run(){
     9         int count=10;
    10         do{
    11             try {
    12                 Thread.sleep((int)(Math.random()*3000));
    13             } catch (InterruptedException e) {
    14                 // TODO Auto-generated catch block
    15                 e.printStackTrace();
    16             }
    17             count--;
    18             p.getGoods(count);
    19             
    20         }while(count>0);
    21     }
    22 }
    CustomerThread.java

    4.测试类

     1 package com.thread.customer;
     2 
     3 public class Test {
     4 
     5     public static void main(String[] args) {
     6         Purchase p=new Purchase();
     7         new CustomerThread(p).start();
     8         new PurchaseThead(p).start();
     9 
    10     }
    11 
    12 }
    Test.java
  • 相关阅读:
    如何切换pip的源
    week0713.5 newspaper 安装问题
    week07 13.3 NewsPipeline之 三News Deduper之 tf_idf 查重
    week07 13.4 NewsPipeline之 三 News Deduper
    week07 13.2 NewsPipeline之 二 News Fetcher
    week07 13.1 NewsPipeline之 一 NewsMonitor
    week06 12 我们准备数据 前端调用rpc 前后端联调一下
    week06 12 后端utils cloudAMQP_client.py 安装pika
    struts2之多文件上传与拦截器(8)
    struts2之单文件上传(7)
  • 原文地址:https://www.cnblogs.com/holly8/p/12359260.html
Copyright © 2011-2022 走看看