Java并发知识总结
jixu ? 8. 并发启动线程的几种方式 Thread t7 = new Thread(timer); t7.start(); Thread.sleep(100) //暂停当前线程 ? class MT extends Thread { private int n; public MyThread( int n ){ super(); this.n=n; } public void run() { for(int i=0;i<n;i++) { System.out.println(i); } } } Class MT implements Runnable{ private int n; public MyTask(int n){ this.n = n; } public void run() { for(int i=0; i<n; i++) { System.out.println(i); } } } new Thread(){ public void run() { for(int i=0; i<10; i++) System.out.println(i); } }.start(); new Thread( ( ) -> { for(int i=0; i<10; i++) System.out.println(i); } ).start();
? java并发API:java.util.concurrent ? 线程池 class ThreadPoolDemo { public static void main(String[] args) { ExecutorService pool=Executors.newCachedThreadPool(); MyTask t1=new MyTask(5); MyTask t2=new MyTask(7); pool.execute(t1); pool.execute(t2); pool.shutdown(); } } class MyTask implements Runnable { int n=10; public MyTask(int n){ this.n=n;} public void run(){ for(int i=0;i<n; i++)System.out.print(i); } } ? ? 实现一个生产者-消费者问题 1 class Producer extends Thread { 2 private CubbyHole cubbyhole; 3 private int number; 4 public Producer(CubbyHole c,int number) { 5 cubbyhole = c; 6 this.number = number; 7 } 8 public void run() { 9 for (int i = 0; i <10; i++) 10 cubbyhole.put(i); 11 } 12 } 13 14 class Consumer extends Thread { 15 private CubbyHole cubbyhole; 16 private int number; 17 public Consumer(CubbyHole c,int number) { 18 cubbyhole = c; 19 this.number = number; 20 } 21 public void run() { 22 int value = 0; 23 for (int i = 0; i <10; i++) 24 value = cubbyhole.get(); 25 } 26 } 27 28 class CubbyHole { 29 private int data[] = new int[3]; 30 private int index = 0; 31 public synchronized int get() { 32 while (index <= 0) { 33 try{ 34 wait(); //waits for notify() from Producer 35 } catch (InterruptedException e) { } 36 } 37 index --; 38 int value = data[index]; 39 System.out.println("Consumer got: " + data[index]); 40 notify(); 41 return value; 42 } 43 public synchronized void put(int value) { 44 while (index >= data.length) { 45 try{ 46 wait(); //waits for notify() from consumer 47 } catch (InterruptedException e) { } 48 } 49 System.out.println("Producer put: " + value); 50 data[index] = value; 51 index ++; 52 notify(); 53 } 54 } 55 56 class ProducerConsumerStack { 57 public static void main(String args[]) { 58 CubbyHole c = new CubbyHole(); 59 Producer p1=new Producer(c,1); 60 Consumer c1=new Consumer(c,1); 61 p1.start(); 62 c1.start(); 63 } 64 } ? ? Ref:https://github.com/CyC2018/CS-Notes/blob/master/notes/Java%20%E5%B9%B6%E5%8F%91.md (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |