Java多线程实例
Thread类的构造方法:public Thread( );public Thread(Runnable target);public Thread(String name);public Thread(Runnable target, String name);public Thread(ThreadGroup group, Runnable target);public Thread(ThreadGroup group, String name);public Thread(ThreadGroup group, Runnable target, String name);public Thread(ThreadGroup group, Runnable target, String name, long stackSize); Runnable target实现了Runnable接口的类的实例。要注意的是Thread类也实现了Runnable接口,因此,从Thread类继承的类的实例也可以作为target传入这个构造方法。 String name线程的名子。这个名子可以在建立Thread实例后通过Thread类的setName方法设置。如果不设置线程的名子,线程就使用默认的线程名:Thread-N,N是线程建立的顺序,是一个不重复的正整数。 ThreadGroup group当前建立的线程所属的线程组。如果不指定线程组,所有的线程都被加到一个默认的线程组中。关于线程组的细节将在后面的章节详细讨论。 long stackSize线程栈的大小,这个值一般是CPU页面的整数倍。如x86的页面大小是4KB。在x86平台下,默认的线程栈大小是12KB。 ================================================ public class MultiThreadsTest{ public static void main(String args[]){ Resource res = new Resource(); ProducerThread p1 = new ProducerThread(res); ProducerThread p2 = new ProducerThread(res); ProducerThread p3 = new ProducerThread(res); p1.start(); p2.start(); p3.start(); new Thread(p1,"p1"); ConsumerThread c1 = new ConsumerThread(res); c1.start(); } } /** 资源类,拥有product,以及生产和消费product的方法 @author hp* */class Resource { private int product = 0; public Resource(){ this.product = 0; } public int getProduct() { return product; } public void setProduct(int product) { this.product = product; } public synchronized void produce(){ if(this.product > 100){ try{ wait(); System.out.println("产品已满,请稍后再生产。"); }catch(Exception e){ e.printStackTrace(); } return; } this.product++; System.out.println("生产一个产品,当前有产品:" + this.product); notifyAll(); } public synchronized void consume(){ if(this.product <= 0){ try{ wait(); System.out.println("缺货,请稍等。"); }catch(Exception e ){ e.printStackTrace(); } return; } this.product--; System.out.println("消费一个产品,当前有产品:" + this.product); notifyAll(); } } /** 生产者,可实例化多个生产者线程实例。调用Resource的生成方法生产product @author hp* */class ProducerThread extends Thread{ private Resource r; public ProducerThread(Resource r){ this.r = r; } public void run(){ while(true){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } r.produce(); } } } /** 消费者,可实例化多个消费者线程实例。调用Resource的消费方法消费product @author hp* */class ConsumerThread extends Thread{ private Resource r; public ConsumerThread(Resource r){ this.r = r; } public void run(){ while(true){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } r.consume(); } } }