一.多線程的小例子
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();
}
}