线程的两种实现方式:
1. 继承Thread类:
public classTest extends Thread{
public void run(){} }
使用:
public staticvoid main(String[] args){
Test t = new Test();
t.strat();
}
2. 实现Runnable接口:
public classTest implements Runnable{
public void run(){} }
使用:
publicstatic void main(String[] args){
Testt = new Test();
Threadthread = new Thread(t);
thread.start();
}
线程的一些常用方法:
static Thread currentThread(): 返回对当前正在执行的线程对象的引用。
String getName(): 返回该线程名称。
void setName(): 设置线程名称。
int getPriority(): 返回线程的优先级。
void setPriority(): 设置线程的优先级。
Thread.State getState(): 返回该线程的状态。
void interrupt(): 中断线程。
static boolean interrupted(): 测试当前线程是否已经中断。
boolean isAlive(): 测试线程是否处于活动状态。
boolean isInterrupt(): 测试线程是否已经中断。
void join(): 等待该线程终止。
void join(long millis):等待该线程终止的时间最长为millis毫秒。
void join(long millis, int nanos):等待该线程终止的时间最长为millis毫秒+nanos纳秒。
void run(): 一般重写或实现。不重写则不执行任何操作并返回。
void start(): 使线程开始执行;Java虚拟机调用该线程的run方法。
String toString(): 返回该线程的字符串表示形式,包括线程名称、优先级和线程组。
线程的一个经典案例(生产者/消费者模式):
产品类:
publicclass Product{
privateint id;
Product(int id){
this.id = id;
}
public StringtoString(){
return “Product:” + id;
}
仓库类:
public classStorage{
//一个元素为Product的数组,长度为5吧
Product p[] = new Product[5];
int index;
//生产方法
public synchronized void produce(Product product){
//当产品达到上限,则不再生产,线程等待
try{
while(index == p.length){
System.out.println(“产品达到上限,停止生产!”);
wait();
}catch(InterruptException e){
e.printStackTrace();
}
}
p[index] = product;
index++;
System.out.println(“生产了一个,总共有”+index+”个”);
}
//消费方法
public synchronized Product consume(){
try{
while(index == 0){
System.out.println(“没有产品了,停止消费!”);
wait();
} catch(InterruptException e){
e.printStackTrace();
}
index --;
System.out.pirntln(“消费了一个,还剩:”+index+”个”);
return p[index];
}
}
生产者类:
publicclass Producer implements Runnable{
private Storage storage;
public Producer (Storage storage){
this.storage =storage;
}
public void run(){
//生产30次
for(int i =0;i<30;i++){
Product p = new Product(i);
storage.produce(p);
try{
//设置随机的休眠时间
Thread.sleep((int)(Math.random()*200));
}catch(InterruptException e){
e.printStackTrance();
}
}
}
}
消费者类:
public class Consumer implements Runnable{
private Storage storage;
public Consumer(Storage storage){
this.storage = storage;
}
public void run(){
//消费30次,且消费比生产慢,也可以调节生产和消费的时间速度看不同效果
for (int i = 0;i<30;i++){
storage.consume();
try{
Thread.sleep((int)(Math.random()*500));
}catch(InterruptException e){
e.printStackTrace();
}
}
}
}
主方法类:
public class ProducersAndConsumers{
public static void main(String[] args){
Storage s = new storage();
Producer p = new Producer(s);
Consumer c = new Consumer(s);
Thread tp = new Thread(p);
Thread tc = new Thread(c);
tp.start();
tc.start();
}
}
运行结果部分内容截图: