1、继承Thread 类
class MyThread extends Thread{
private int ticket=5;
public void run(){
for(int i=0;i<10;i++){
if(ticket>0){
System.out.println("卖票:ticket="+ticket--);
}
}
}
}
public static void main(String args[]){
MyThread mt1=new MyThread();
MyThread mt2=new MyThread();
mt1.start();
mt2.start();
}
//通过Thread类实现多线程,3个线程分别卖了各自的5张票,并没有达到资源共享的目的
2、实现Runnable接口
class MyThread implements Runnable{
private int ticket=5;
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println("卖票:ticket="+ticket--);
}
}
}
public static void main(String args[]){
MyThread mt=new MyThread();
new Thread(my).start();
new Thread(my).start();
new Thread(my).start();
}
//实现Runnable接口启动3个线程一共才卖了5张票,即ticket属性被所有的线程共享
3、线程的停止:在多线程的开发中,通过设置标志位停止一个线程的运行
class MyThread implements Runnable{
private boolean flag=true;
@Override
public void run() {
while(this.flag){
while(true){
System.out.println("线程中的耗时操作");
}
}
}
public void stop(){
this.flag=false;
}
}