1.
继承Runnable的用法:
关键是继承Runnable并且必须实现run()函数,通过run函数启动线程,似乎多个线程不可以并行
TestRunnable.java
package TestPackage;
import java.lang.Runnable;
import java.lang.Runnable;
package TestPackage;
import java.lang.Runnable;
public class TestRunnable implements Runnable {
public void run() {
// TODO Auto-generated method stub
System. out.println("hello world1 !" );
try {
Thread. sleep(1000);
} catch (InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System. out.println("hello world2 !" );
}
}
使用语句:
TestRunnable thread = new TestRunnable();
TestRunnable thread1 = new TestRunnable();
thread.run();
thread1.run();
2.
继承Thread方法
继承Thread方法之后,实现run()函数,创建该对象运行start()函数即可启动线程,多个线程可以并行
TestThread.java
package TestPackage;
public class TestThread extends Thread {
public void run() {
System. out.println("hello Thread!" );
try {
Thread. sleep(2000);
} catch (InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System. out.println("hello Thread!" );
}
}
使用语句:
TestThread tt = new TestThread();
TestThread tt1 = new TestThread();
tt.start();
tt1.start();
3.
带任务队列的线程模型
这是生产者消费者模式,生产者消费者都继承Thread,然后共享一个阻塞队列(BlockingQueue)
TestBlockingQueue.java
package TestPackage;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class TestBlockingQueue {
public static void runConsumerProducer() {
BlockingQueue<Integer> q = new LinkedBlockingQueue<Integer>(10);
Producer producer = new Producer(q );
Consumer consumer1 = new Consumer(q);
Consumer consumer2 = new Consumer(q);
producer.start();
consumer1.start();
consumer2.start();
}
}
class Producer extends Thread{
final private BlockingQueue<Integer> taskQueue;
public Producer(BlockingQueue<Integer> q ) {
taskQueue = q ;
}
public void run() {
int i = 0;
while (true ) {
try {
System. out.println("put " + i );
taskQueue.put(i );
} catch (InterruptedException e ) {
// TODO Auto-generated catch block
e. printStackTrace();
}
++ i;
try {
Thread. sleep(100);
} catch (InterruptedException e ) {
// TODO Auto-generated catch block
e. printStackTrace();
}
}
}
}
class Consumer extends Thread {
final private BlockingQueue<Integer> taskQueue;
public Consumer(BlockingQueue<Integer> q ) {
taskQueue = q ;
}
public void run() {
while (true ) {
try {
System. out.println("get :" + taskQueue .take());
} catch (InterruptedException e ) {
// TODO Auto-generated catch block
e. printStackTrace();
}
try {
Thread. sleep(1000);
} catch (InterruptedException e ) {
// TODO Auto-generated catch block
e. printStackTrace();
}
}
}
}
使用语句:
TestBlockingQueue.runConsumerProducer();