多线程

来源:互联网 发布:室内设计网络教育 编辑:程序博客网 时间:2024/06/03 13:08

多线程



 

我上课整理出来的多线程的例子,大家看看。包括:

使用Thread创建线程;
使用Runnable创建线程;
实例:让人能够同时说话和开车;
实例:模拟生成者和消费者。
1、使用Thread实现多线程

示例代码:

view plaincopy to clipboardprint?
package ch18;  
 
public class ThreadTest extends Thread{  
    public boolean b=false;  
    public static void main(String[] args) {  
        ThreadTest thread = new ThreadTest();  
        thread.setName("child");  
        thread.start();  
          
        try {  
            thread.join();  
        } catch (InterruptedException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }  
          
        ThreadTest thread1 = new ThreadTest();  
        thread1.setName("child-------");  
        thread1.start();  
          
        for(int i=0;i<5;i++){  
            try {  
                sleep(100);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
            System.out.println(currentThread().getName()+":"+i);  
        }  
          
        thread.b = true;  
        thread1.b = true;  
    }  
 
    public void run(){  
        for(int i=0;i<10;i++){  
            try {  
                sleep(100);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
            System.out.println(currentThread().getName()+":"+i);  
            if(b)  
                break;  
        }  
    }  

package ch18;

public class ThreadTest extends Thread{
 public boolean b=false;
 public static void main(String[] args) {
  ThreadTest thread = new ThreadTest();
  thread.setName("child");
  thread.start();
  
  try {
   thread.join();
  } catch (InterruptedException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  
  ThreadTest thread1 = new ThreadTest();
  thread1.setName("child-------");
  thread1.start();
  
  for(int i=0;i<5;i++){
   try {
    sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println(currentThread().getName()+":"+i);
  }
  
  thread.b = true;
  thread1.b = true;
 }

 public void run(){
  for(int i=0;i<10;i++){
   try {
    sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println(currentThread().getName()+":"+i);
   if(b)
    break;
  }
 }
}
 

2、使用Runnable实现多线程

示例代码:

view plaincopy to clipboardprint?
package ch18;  
 
public class RunnableTest implements Runnable{  
 
    public static void main(String[] args) {  
        Runnable r1 = new RunnableTest();  
        Thread thread = new Thread(r1,"t1");  
        thread.start();  
        thread.setPriority(9);  
          
        Thread thread2 = new Thread(r1,"t2");  
        thread2.start();  
        thread2.setPriority(2);  
    }  
      
    public void run(){  
        for(int i=0;i<100;i++){  
            System.out.println(Thread.currentThread().getName()+":"+i);  
        }  
    }  

package ch18;

public class RunnableTest implements Runnable{

 public static void main(String[] args) {
  Runnable r1 = new RunnableTest();
  Thread thread = new Thread(r1,"t1");
  thread.start();
  thread.setPriority(9);
  
  Thread thread2 = new Thread(r1,"t2");
  thread2.start();
  thread2.setPriority(2);
 }
 
 public void run(){
  for(int i=0;i<100;i++){
   System.out.println(Thread.currentThread().getName()+":"+i);
  }
 }
}
 

3、实例:让人能够同时说话和开车

示例代码:

view plaincopy to clipboardprint?
package ch19;  
 
import static java.lang.System.out;  
 
public class Person implements Runnable{  
 
    int speakNo=0;  
    int driveNo=0;  
      
    private boolean canStop=false; // 是否停止线程  
      
    public static void main(String[] args) {  
        Person person = new Person();  
          
        Thread t1 = new Thread(person,"speak"); // 第二个参数给出线程的名字  
        Thread t2 = new Thread(person,"drive");  
          
        t1.setPriority(8);  
        t2.setPriority(4);  
          
        t1.start();  
        t2.start();  
          
        try {  
            Thread.currentThread().sleep(1000);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
          
        person.setCanStop(true);  
    }  
      
    public void run(){  
        while(true){  
            String name = Thread.currentThread().getName(); // 得到当前线程   
的名字  
            if(name.equals("speak")){  
                speak();  
            }else{  
                drive();  
            }  
            if(canStop){  
                break;  
            }  
        }  
    }  
      
    public void drive(){  
        out.println("正在--------------开车!"+driveNo++);  
//      try {  
//          Thread.currentThread().sleep(5);  
//      } catch (InterruptedException e) {  
//          e.printStackTrace();  
//      }  
    }  
      
    public void speak(){  
        out.println("正在说话!"+speakNo++);  
//      try {  
//          Thread.currentThread().sleep(5);  
//      } catch (InterruptedException e) {  
//          e.printStackTrace();  
//      }  
    }  
 
    public boolean isCanStop() {  
        return canStop;  
    }  
 
    public void setCanStop(boolean canStop) {  
        this.canStop = canStop;  
    }  
      
      

package ch19;

import static java.lang.System.out;

public class Person implements Runnable{

 int speakNo=0;
 int driveNo=0;
 
 private boolean canStop=false; // 是否停止线程
 
 public static void main(String[] args) {
  Person person = new Person();
  
  Thread t1 = new Thread(person,"speak"); // 第二个参数给出线程的名字
  Thread t2 = new Thread(person,"drive");
  
  t1.setPriority(8);
  t2.setPriority(4);
  
  t1.start();
  t2.start();
  
  try {
   Thread.currentThread().sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  
  person.setCanStop(true);
 }
 
 public void run(){
  while(true){
   String name = Thread.currentThread().getName(); // 得到当前线程
的名字
   if(name.equals("speak")){
    speak();
   }else{
    drive();
   }
   if(canStop){
    break;
   }
  }
 }
 
 public void drive(){
  out.println("正在--------------开车!"+driveNo++);
//  try {
//   Thread.currentThread().sleep(5);
//  } catch (InterruptedException e) {
//   e.printStackTrace();
//  }
 }
 
 public void speak(){
  out.println("正在说话!"+speakNo++);
//  try {
//   Thread.currentThread().sleep(5);
//  } catch (InterruptedException e) {
//   e.printStackTrace();
//  }
 }

 public boolean isCanStop() {
  return canStop;
 }

 public void setCanStop(boolean canStop) {
  this.canStop = canStop;
 }
 
 
}
 

4、实例:模拟生成者消费者模型

示例代码:

view plaincopy to clipboardprint?
package ch19;  
 
import static java.lang.System.out;  
 
// 第一步:实现Runnable接口,并且实现run方法  
public class Factory implements Runnable {  
    // 第二步:定义表示库存变量quantity,quantity的值会影响生产和消费这两个方法的执   
行,有产品才可以消费,仓库没有满才可以生产  
    // 库存,初始为0,最大为10  
    private int quantity = 0;  
    // 第六步:创建成员变量canStop控制线程的结束,主线程中修改控制变量的值,在生产和   
消费线程中判断该变量的值,然后结束线程。  
      
    private boolean canStop = false;  
 
    public int getQuantity() {  
        return quantity;  
    }  
 
    public void setQuantity(int quantity) {  
        this.quantity = quantity;  
    }  
 
    public boolean isCanStop() {  
        return canStop;  
    }a  
 
    public void setCanStop(boolean canStop) {  
        this.canStop = canStop;  
    }  
 
    // 第四步:创建工厂对象,然后创建生产和消费的线程并启动  
    public static void main(String args[]) {  
        Factory factory = new Factory();  
 
        Thread t1 = new Thread(factory, "producer1");  
        Thread t2 = new Thread(factory, "producer2");  
        Thread t3 = new Thread(factory, "consumer1");  
        Thread t4 = new Thread(factory, "consumer2");  
 
        t1.start();  
        t2.start();  
        t3.start();  
        t4.start();  
 
        try {  
            Thread.currentThread().sleep(300);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
 
        factory.setCanStop(true);  
    }  
 
    // 第五步:实现run方法,根据当前线程的任务去调用相应的方法,或者去生产 或者消费  
    public void run() {  
        String threadName = Thread.currentThread().getName();  
        while (true) {  
            if (threadName.startsWith("producer")) {  
                produce();  
            } else {  
                consume();  
            }  
            if(canStop)  
                break;  
        }  
    }  
 
    // 第三步:定义消费和生产的方法  
    public synchronized void consume() {  
        // 判断是否有商品  
        while (quantity == 0) {  
            try {  
                wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
 
        // 消费商品  
        quantity--;  
        String threadName = Thread.currentThread().getName();  
        out.println(threadName + "消费了一个商品!");  
        try {  
            Thread.currentThread().sleep(50);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
 
        notifyAll();  
    }  
 
    // 生成商品  
    public synchronized void produce() {  
        // 判断仓库是否已经满了,如果满了,就等待  
        while (quantity == 10) {  
            try {  
                wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
 
        // 生产  
        quantity++;  
        String threadName = Thread.currentThread().getName();  
        out.println(threadName + "生产了一个商品!");  
        try {  
            Thread.currentThread().sleep(50);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
 
        notifyAll();  
    }  
}

原创粉丝点击