package thread;
/**
* 线程有2中创建方式
* 方式一:
* 继承Thread 并重写run方法,
* 并再run方法中添加线程要执行的代码
*
* @author 清风已来
*
*/
public class ThreadDemo1 {
public static void main(String[] args) {
Thread t1 = new MyThread1();
Thread t2 = new MyThread2();
/**
* 需要注意,启动线程要调用该线程的start方法
* 而不是调用run方法,当start方法调用后,线程纳入线程调用
* 一旦该线程获取了CPU的时间片段后,该线程会自动调用
*/
t1.start();//启动1线程
t2.start();//启动2线程
}
}
/*此种创建线程的方式有2个不足之处:
* 1:由于JAVA是单继承的这就导致了若继承了Thread
* 就不能再继承其他类,在实际开发中会有诸多不边。
* 2:定义线程的同时在run方法中定义了线程要执行的任务
* 这就导致了线程与任务有一个必然的耦合关系,不利于
* 线程的重用
* 强藕合 会让该对象不灵活 依赖度太大,不利于线程的重用
*
*/
class MyThread1 extends Thread{
public void run() {
for(int i=0;i<100;i++) {
System.out.println("你谁啊?");
}
}
}
class MyThread2 extends Thread{
public void run() {
for (int i=0;i<100;i++) {
System.out.println("我是查水表的");
}
}
}
package thread;
/**
* 线程有2中创建方式 方式二: 实现Runnable接口单独定义线程任务
*
*
* @author 清风已来
*
*/
public class ThreadDemo2 {
public static void main(String[] args) {
Runnable r1 = new MyRunnable1();
Runnable r2 = new MyRunnable2();
Thread t1 =new Thread(r1);
Thread t2 =new Thread(r2);
t1.start();
t2.start();
}
}
class MyRunnable1 implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("你是谁啊?");
}
}
}
class MyRunnable2 implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("我是查水表的!");
}
}
}