java多线程的原理是:
1.虚拟的cpu: 继承java.lang.Thread类,完成线程的机制(内部是native方法,源代码中是private static native void registerNatives())
2.运行线程体: 覆盖run()方法。将方法体在虚拟的cpu上运行(源代码上式:public void run() )。
3. 启动线程: 调用Start()方法,就是先启动虚拟的cpu(即在调用run()方法运行)。
下面用生产者-消费者做个例子:
import java.util.ArrayList;
import java.util.List;
public class ThreadTest {
List<Object> basket = new ArrayList<Object>();
public synchronized Object getFood() {
if (basket.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
Object food = basket.get(0);
basket.clear();// 清空盘子
notify();// 唤醒阻塞队列的某线程到就绪队列
System.out.println("拿到食物");
return food;
}
public synchronized void putFood(Object food) {
if (basket.size() > 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
basket.add(food);// 往盘子里放食物
notify();// 唤醒阻塞队列的某线程到就绪队列
System.out.println("放入食物");
}
static class ProduceThread extends Thread{
private ThreadTest threadTest;
private Object food=new Object();
public ProduceThread(ThreadTest threadTest){
this.threadTest=threadTest;
}
public void run(){
for(int i=0;i<5;i++){
threadTest.putFood(food);
}
}
}
static class ConsumeThread extends Thread{
private ThreadTest threadTest;
public ConsumeThread(ThreadTest threadTest){
this.threadTest=threadTest;
}
public void run(){
for(int i=0;i<5;i++){
threadTest.getFood();
}
}
}
public static void main(String args[]){
try {
ThreadTest threadTest=new ThreadTest();
Thread add=new Thread(new ProduceThread(threadTest));
Thread get=new Thread(new ConsumeThread(threadTest));
add.start();
get.start();
add.join();
get.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("测试结束");
}
}