1.继承Thread类
2.实现Runnable接口(并发资源问题)
线程与进程不同,进程的内存是单独的,而线程是共用的,这里的共用体现在了如果你创建了一个资源对象,再用这个资源对象创建出的线程对象的内存是共用的。
- 继承Thread类
这个方法好处是代码写起来简洁,因为本身就是线程了,但坏处就是有些需要继承父类的类不能用这个方法,所以使用第二种实现接口的方法会更好。
public class MutiThreadClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
new MutiThread("Thread A").start();
new MutiThread("Thread B").start();
new MutiThread("Thread C").start();
}
}
public class MutiThread extends Thread{
private String str;
public MutiThread(String str) {
this.str=str;
}
public void run() {//每个线程在main类调用start()方法后都会转到run()
System.out.println("Hello!"+str);
}
}
输出异步的。
Hello!Thread A
Hello!Thread C
Hello!Thread B
- 实现Runnable接口
避免了java单继承的局限,更好的选择,而且资源对象也被单独出来了,更符合java面向对象的思想。
public class RunnableClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new RunnableThread("Thread A")).start();
new Thread(new RunnableThread("Thread B")).start();
new Thread(new RunnableThread("Thread C")).start();
}
}
public class RunnableThread implements Runnable {
private String str;
public RunnableThread(String str) {
this.str=str;
}
public void run() {
System.out.println("Hello!"+str);
}
}
并发资源问题
public class MutiThreadClient {
public static void main(String[] args) {
RunnableThread rt = new RunnableThread(); // 定义资源对象
new Thread(rt).start(); // 第一个线程启动
new Thread(rt).start(); // 第二个线程启动
new Thread(rt).start(); // 第三个线程启动
}
}
public class RunnableThread implements Runnable {
private int ticket = 5; // 定义总票数
@Override
public void run() { // 线程的主体方法
for (int x = 0; x < 100; x++) { // 进行100次的卖票处理
if (this.ticket > 0) { // 有剩余票
System.out.println("卖票,ticket = " + this.ticket--);
}
}
}
}
output:
卖票,ticket = 5
卖票,ticket = 3
卖票,ticket = 1
卖票,ticket = 4
卖票,ticket = 2