实现Runnable
- 定义MyRunnable类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建对象,调用start()方法启动线程
package com.Jinone.www;
import java.io.IOException;
public class TextThread implements Runnable {
@Override
public void run() {
for(int i=0;i<20;i++) {
System.out.println("我在看代码~"+i);
}
}
public static void main(String[] args) {
TextThread textThread=new TextThread();
Thread thread=new Thread(textThread);
for(int i=0;i<20;i++) {
System.out.println("我在学java多线程~"+i);
}
thread.start();
}
}
小结
- 继承Thread类
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免oop单继承限性
- 实现Runnable接口
-
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
package com.Jinone.www;
import java.io.IOException;
public class TextThread implements Runnable {
private int as=1;
private static int asone,astwo,asthree;
@Override
public void run() {
while(true) {
if(as>=100) {
System.out.println("小明一共抢到了"+asone+"张火车票");
System.out.println("小王一共抢到了"+astwo+"张火车票");
System.out.println("小米一共抢到了"+asthree+"张火车票");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"抢到了第"+as+++"张火车票!");
if(Thread.currentThread().getName().equals("小明")) {
asone++;
}
if(Thread.currentThread().getName().equals("小王")) {
astwo++;
}
if(Thread.currentThread().getName().equals("小米")) {
asthree++;
}
}
}
public static void main(String[] args) {
TextThread textThread=new TextThread();
new Thread(textThread,"小明").start();
new Thread(textThread,"小王").start();
new Thread(textThread,"小米").start();
}
}
结果:存在资源共享问题!