多线程编程
Posted shuzi0806
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程编程相关的知识,希望对你有一定的参考价值。
一: 两种实现方式:
1.继承Thread类重写run方法
2.继承Runnable接口重写run方法(通常用这种,java单继承的局限性,后期还想继承其他类会无从下手)
二:简单demo1(多线程模拟买票)
package 多线程;
public class BuyTicket {
public static void main(String[] args) {
TickThread tt = new TickThread();
Thread t1 = new Thread(tt,"张三");
Thread t2 = new Thread(tt,"李四");
Thread t3 = new Thread(tt,"王五");
t1.start();
t2.start();
t3.start();
}
}
class TickThread implements Runnable{
private int total = 10;
@Override
public void run() {
while (total>=1) {
total--;
System.out.println(Thread.currentThread().getName() + "买了票,剩余" + total + "张");
}
System.out.println(Thread.currentThread().getName()+"发现售罄");
}
}
由于资源没有加锁,导致数据异常问题
三 简单demo2(模拟龟兔赛跑)
package 多线程;
public class RunGame {
public static void main(String[] args) {
Runner rn = new Runner();
Thread rabbit = new Thread(rn,"rabbit");
Thread tortoise = new Thread(rn,"tortoise");
rabbit.start();
tortoise.start();
}
}
class Runner implements Runnable{
private int stage = 100;
private String winner=null;
@Override
public void run() {
for(int i=1;i<=100;i++){
if(isOver(i)==true) {
Thread.currentThread().interrupt();
break;
}
}
}
boolean isOver(int step){
if (winner!=null){
return true;
}else{
if(step==100){
System.out.println(Thread.currentThread().getName()+"胜利!");
winner=Thread.currentThread().getName();
return true;
}else{
System.out.println(Thread.currentThread().getName()+"->"+step);
return false;
}
}
}
}
以上是关于多线程编程的主要内容,如果未能解决你的问题,请参考以下文章