JAVA(四)回憶基礎(chǔ)掃盲多線程

一.多線程的小例子

import org.junit.Test;

public class TestThread {    
@Test
  public void test1(){
  實(shí)例化線程對(duì)象
      new MyThread("T1").start();
      new MyThread("T2").start();
  }
  定義線程類實(shí)現(xiàn)類
class MyThread extends Thread{
    private String name ;
     構(gòu)造函數(shù)傳入值,獲取線程的名稱
    public MyThread(String name) {
        this.name = name;
    }
     初始化線程執(zhí)行條數(shù)
    public void run() {
        for(int i = 0; i <= 100 ; i ++){
            System.out.println(name + " : " + i);
            yield();
        }
    }
}

}

四.構(gòu)建線程池

import java.util.LinkedList;
票池,創(chuàng)建
public class TicketPool {
定義pool池,使其是鏈表對(duì)象
private LinkedList<Integer> pool = new LinkedList<Integer>();
生產(chǎn)方法
public /*synchronized*/ int add(Integer i){
    pool.add(i);
    return i ;
 }
消費(fèi)方法
public /*synchronized*/ int remove(){
    try {
        while(pool.isEmpty()){
            Thread.sleep(50);  緩解進(jìn)程搶占問題
        }
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return pool.removeFirst();
   }
}

五.消費(fèi)者類

public class Consumer extends Thread {
private String name ;
 
private TicketPool pool ;
獲取線程的name和pool實(shí)例
public Consumer(String name,TicketPool pool) {
    super();
    this.name = name;
    this.pool = pool ;
}
定義執(zhí)行方法
public void run() {
    while(true){
        int n = pool.remove();
        System.out.println(name + " remove : " + n);
       }
  }
}

六.生產(chǎn)者類

public class Producer extends Thread {
    private static int index = 0 ;
    private String name ;
 
private TicketPool pool ;
 
public Producer(String name,TicketPool pool) {
    super();
    this.name = name;
    this.pool = pool ;
}

public void run() {
    while(true){
        int n = pool.add(index ++ );
        System.out.println(name + " add : " + n);
    }
}

}

七.定義執(zhí)行函數(shù)類

public class App {

public static void main(String[] args) {
    TicketPool pool = new TicketPool();
    Producer p1 = new Producer("P1", pool);
    Producer p2 = new Producer("P2", pool);
    Consumer c1 = new Consumer("C1", pool);
     
    p1.start();
    p2.start();
    c1.start();
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容