创建线程的方式 一:
继承Thread,重写run方法,run方法中的代码就是需要让线程并发执行的代码
public class ThreadDemo1 {
public static void main(String[] args) {
Thread ta = new MyThread1();
Thread tb = new MyThread2();
// 启动线程要调用线程的start方法,而不需要直接调用run方法!
// start方法调用完毕后,run方法会很快的被调用.
ta.start();
tb.start();
}
}
/**
* 这种创建线程方式的不足
* 1:由于java是单继承的,这就导致若继承了Thread当前类就无法继承其他类来复用方法
* 2:由于在当前类内部重写run方法,这就导致线程与其要执行的任务有一个必然的耦合关系.不利于
* 线程复用.
*/
class MyThread1 extends Thread{
public void run(){
for(int i=0;i<5000;i++){
System.out.println(“线程一”);
}
}
}
class MyThread2 extends Thread{
public void run(){
for(int i=0;i<5000;i++){
System.out.println(“线程二”);
}
}
}
// 创建线程的方式二:
// 实现Runnable接口并重写run方法来单独定义线程
public class ThreadDemo2 {
public static void main(String[] args) {
//创建线程要执行任务
Runnable rc = new MyRunnable3();
Runnable rd = new MyRunnable4();
// 创建线程
Thread tc = new Thread(rc);
Thread td = new Thread(rd);
tc.start();
td.start();
}
}
class MyRunnable3 implements Runnable{
public void run() {
for(int i=0;i<5000;i++){
System.out.println(“线程三”);
}
}
}
class MyRunnable4 implements Runnable{
public void run() {
for(int i=0;i<5000;i++){
System.out.println(“线程四”);
}
}
}