1. 繼承Thread類
重寫Thread的run()方法笙僚,把線程運(yùn)行邏輯放在其中
package com.threadtest;
class MyThread extends Thread{
private int ticket = 10;
private String name;
public MyThread(String name){
this.name =name;
}
public void run(){
for(int i =0;i<500;i++){
if(this.ticket>0){
System.out.println(this.name+"賣票---->"+(this.ticket--));
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread mt1= new MyThread("一號窗口");
MyThread mt2= new MyThread("二號窗口");
MyThread mt3= new MyThread("三號窗口");
mt1.start();
mt2.start();
mt3.start();
}
}
2. 實(shí)現(xiàn)Ruunable接口
package com.threadtest;
class MyThread1 implements Runnable{
private int ticket =10;
private String name;
public void run(){
for(int i =0;i<500;i++){
if(this.ticket>0){
System.out.println(Thread.currentThread().getName()+"賣票---->"+(this.ticket--));
}
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//設(shè)計三個線程
MyThread1 mt = new MyThread1();
Thread t1 = new Thread(mt,"一號窗口");
Thread t2 = new Thread(mt,"二號窗口");
Thread t3 = new Thread(mt,"三號窗口");
// MyThread1 mt2 = new MyThread1();
// MyThread1 mt3 = new MyThread1();
t1.start();
t2.start();
t3.start();
}
}
3. 實(shí)現(xiàn)Callable接口
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("******come here");
//暫停一會兒線程
try{
TimeUnit.SECONDS.sleep(4);
}catch (InterruptedException e)
{
e.printStackTrace();
}
return 1024;
}
}
public class CallableDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask futureTask = new FutureTask(new MyThread());
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start();
System.out.println(Thread.currentThread().getName()+"main****計算完成");
System.out.println(futureTask.get());
}
}
需要用FutureTask關(guān)聯(lián)runnable接口和callable接口晃痴。
Callable接口的好處是不會讓住線程阻塞等待疗韵,而是會繼續(xù)主線程尿招。