多线程 |
在创建线程对象时就要明确运行那段代码。
package Second;
class Ticket extends Thread{
int tickets;
public Ticket(int ticket) {
super();
this.tickets = ticket;
}
@Override
public void run(){
while(tickets>0){
tickets--;
try {
Thread.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+">>>"+tickets);
}
}
}
public class TicketTest{
public static void main(String[] args) {
Ticket ticket=new Ticket(100);
ticket.start();//由于是继承thread,所以ticket对象本身有start方法
Thread t1=new Thread(ticket);//这两个是通过创建父类对象调用子类方法的多态现象
Thread t2=new Thread(ticket);
t1.start();
t2.start();
}
}//打印结果
/* Thread-0>>>10
Thread-2>>>10
Thread-1>>>8
Thread-0>>>7
Thread-2>>>6
Thread-1>>>5
Thread-2>>>4
Thread-0>>>4
Thread-1>>>2
Thread-0>>>1
Thread-2>>>0
Thread-1>>>0
Thread-0>>>0
*/5.开启start并调用runnable的子类对象run;
class Ticket2 implements Runnable{
int tickets;
public Ticket2(int ticket) {
super();
this.tickets = ticket;
}
@Override
public void run(){
while(tickets>0){
tickets--;
try {
Thread.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+">>>"+tickets);
}
}
}
public class TicketTest2{
public static void main(String[] args) {
Ticket2 ticket=new Ticket2(100);
//ticket.start();由于是实现Runnable,此时Ticket不在拥有start的方法。
Thread t1=new Thread(ticket);//这两个是通过创建父类对象调用子类方法的多态现象
Thread t2=new Thread(ticket);
Thread t3=new Thread(ticket);
t1.start();
t2.start();
t3.start();
}
}//打印结果
/*Thread-2>>>9
Thread-1>>>9
Thread-0>>>8
Thread-1>>>6
Thread-0>>>6
Thread-2>>>5
Thread-0>>>3
Thread-2>>>2
Thread-1>>>1
Thread-2>>>0
Thread-1>>>0
Thread-0>>>0*/就是那个判断了,没执行的问题。多语句的时候,同时又操作了共享数据时,在上面的卖票程序中,我们可以看到,结果出现了不该出现的0号票。
同步书写的前提:
1.必须要有两个或者连着以上的线程
2.必须是多个线程 使用同一个锁,才能叫同步。必须保证同一段代码只有一个线程运行。
黑马程序员——java多线程基础知识1,布布扣,bubuko.com
原文地址:http://zhangwei9004.blog.51cto.com/8886503/1409736