一、继承Thread类创建多线程
public class Demo{
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
//子线程执行的操作
}
}
注意:开启子线程要调用start()方法而不是调用run方法
二、实现Runnable接口创建多线程
public class Demo{
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
//子线程执行的操作
}
}
第二种方式相对于第一种方式有哪些优势:
1、避免java单继承带来的局限性(第一种方式继承Thread类后就不能继承别的类,从而给程序扩展带来不便)
2、第一种方式不能实现线程类变量共享,而第二种方式可以,例如下面这种情况
public class Demo{
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();
thread1.start();
thread2.start();
thread3.start();
}
}
class MyThread implements Thread{
int count = 10;
@Override
public void run() {
//子线程执行的操作
count--;
}
}
由于不同的线程对象,有不同的内存副本,导致count–只是操作当前线程对象中的count不会影响其他线程,从而导致无法共享变量。
改进方式如下
public class Demo{
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
}
}
class MyRunnable implements Runnable{
int count = 10;
@Override
public void run() {
//子线程执行的操作
count --;
}
}
上面代码实现了count变量的共享,但要注意线程安全问题