1.继承Thread类,重写run方法
创建形式如下:
public class MyThread extends Thread {
private int times = 5 ;
private String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() {
while(times > 0){
times--;
System.out.println(name + "售出一张票:" + times);
}
}
}
public class TestThread {
public static void main(String[] args) {
MyThread trd1 = new MyThread("窗口一");
MyThread trd2 = new MyThread("窗口二");
MyThread trd3 = new MyThread("窗口三");
trd1.start();
trd2.start();
trd3.start();
}
}
2.实现Runnable接口,重写run方法
实现形式如下:
public class MyRunnable implements Runnable { private int times = 5 ; @Override public void run() { while(times > 0){ times--; System.out.println(Thread.currentThread().getName() + "售出一张票:" + times); } } }
public class MyRunnable implements Runnable {
private int times = 5 ;
@Override
public void run() {
while(times > 0){ times--;
System.out.println(Thread.currentThread().getName() + "售出一张票:" + times);
}
}
}
public class TestRunnable {
public static void main(String[] args) {
MyRunnable mrt1 = new MyRunnable();
Thread t1 = new Thread(mrt1,"窗口一");
Thread t2 = new Thread(mrt1,"窗口二");
Thread t3 = new Thread(mrt1,"窗口三");
t1.start();
t2.start();
t3.start();
}
}