1.创建多线程程序的第一种方式:thread的子类
实现步骤:
1.创建一个thread的子类。
2.重写thread的子类中的Run方法,设置线程任务。
3.创建thread的子类对象。
4.调用thread中的start方法,开启新的线程,执行run方法。
/**
*
* @author jianyeli
*/
public class MyThread extends Thread {
//重写父类Thread中的run方法,设置线程任务
public void run(){
for(int i =0;i<20;i++){
System.out.println("run线程执行");
}
}
}
public class MyThread extends Thread {
//重写父类Thread中的run方法,设置线程任务
public void run(){
for(int i =0;i<20;i++){
System.out.println("run线程执行");
}
}
}
2. 创建多线程程序的第二种方式:实现Runnable接口
实现步骤:
1.创建一个Runnable的实现类。
2.在实现类中重写Runnable接口的Run方法,设置线程任务。
3.创建一个Runnable接口的现实类对象。
4.调用Thread类中的Start方法,开启新的线程,执行Run方法。
public class TicketThread implements Thread{
private int ticket = 10;
public void run(){
for(int i =0;i<10;i++){
synchronized (this){
if(this.ticket>0){
try {
Thread.sleep(100);//每100mlls打印一次
System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] arg){
TicketThread t1 = new TicketThread();
new Thread(t1,"线程1").start();
new Thread(t1,"线程2").start();
}
}