使用synchronized 、wait() 、notifyAll()方法实现 生产者消费者模型 public class ZyDemo01 { private static int num = 0; private static final int FULL = 10; private static final String D = "d"; static class Prooducre implements Runnable { @Override public void run() { synchronized (D) { while (true) { if (num == FULL) { try { D.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } num++; System.out.println(Thread.currentThread().getName() + "生产者:" + num); D.notifyAll(); } } } } static class Consumer implements Runnable { @Override public void run() { synchronized (D) { while (true) { if (num == 0) { try { D.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } num--; System.out.println(Thread.currentThread().getName() + "消费者:" + num); D.notifyAll(); } } } } public static void main(String[] args) { Prooducre producre = new Prooducre(); Consumer consumer = new Consumer(); Thread t1 = new Thread(producre); Thread t2 = new Thread(consumer); t1.start(); t2.start(); } }
//使用3种不同的方式创建线程
static class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } return null; } } static class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(this.getName() + ":" + i); } } } static class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } } public class text { public static void main(String[] args) { MyThread t1 = new MyThread(); MyRunnable myRunnable = new MyRunnable(); Thread t2 = new Thread(myRunnable, "t2"); MyCallable myCallable = new MyCallable(); FutureTask<Integer> task = new FutureTask<>(myCallable); Thread t3 = new Thread(task); t1.setName("t1"); t3.setName("t3"); t1.start(); t2.start(); t3.start(); } } }
// 测试3种不同线程池,体会下区别 public static void main(String[] args) { ExecutorService s1= Executors.newCachedThreadPool(); ExecutorService s2= Executors.newFixedThreadPool(3); ExecutorService s3= Executors.newSingleThreadExecutor(); for (int i = 0; i < 10; i++) { final int index=i; ExecutorService.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+":"+index); } }) } } }
新建状态 - 使用new关键字创建之后进入的状态,此时线程并没有开始执行。
就绪状态 - 调用start方法后进入的状态,此时线程还是没有开始执行。
运行状态 - 使用线程调度器调用该线程后进入的状态,此时线程开始执行,当线程的时间片执行完 毕后任务没有完成时回到就绪状态。
消亡状态 - 当线程的任务执行完成后进入的状态,此时线程已经终止。
阻塞状态 - 当线程执行的过程中发生了阻塞事件进入的状态,如:sleep方法,阻塞状态解除后进入就绪状态。