宗策

导航

多线程,线程创建的有两种方式

package seday08.thread;
/**
* @author xingsir
* 线程允许并发执行多个代码片段
* 方式一:定义一个类继承Thread并重写run方法。run方法用来定义需要线程并发执行的任务代码
*/
public class ThreadDemo1 {

public static void main(String[] args) {
Thread t1 =new MyThread1();//父类应用调用子类对象
Thread t2=new MyThread2();
/*
* 不是直接调用run方法,而是启动线程要调用start,
* start方法调用完毕后,线程纳入线程调度器。当该线程第一次获得CPU时间开始运行时,其run方法会自动被调用。
* 线程纳入线程调度器后,只能被动的等待分配CPU的时间片,得到时间片后,CPU便会运行该线程的任务代码,
* 时间片用完后,CPU离开,此时线程调度会再分配时间片给某个线程使其运行。
* 线程调度器分配时间片的概率是一样的,但是所有并发运行的线程不保证"一人一次"这样均匀的分配时间片。
*/
t1.start();//启动线程要调用start,而不是直接调用run方法
t2.start();

}

}
/*
* 第一种创建线程的方式
* 优点:创建简单,当临时需要执行某个任务时使用这种方式创建更直接
* 缺点:由于java是单继承的,这会导致我们继承了线程以后就不能再继承其他类去复用方法,实际开发非常不便定义线程的同时重写run方法,将任务也一同定义出来
* 这会导致线程与任务有一个必然耦合关系,不利于线程的重用。
*/
class MyThread1 extends Thread{//继承
public void run() {
for(int i=0;i<1000;i++) {//循环
System.out.println("一块黄金");
}
}
}
class MyThread2 extends Thread{//继承
public void run() {
for(int i=0;i<1000;i++) {//循环
System.out.println("两片翡翠");
}
}
}

//================================================================================

package seday08.thread;

/**
* @author xingsir
* 第二种创建线程的方式:实现Runnable接口单独定义线程任务
*/
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();
}

}
//创建MyRunnable1类并实现接口Runnable
class MyRunnable1 implements Runnable {
public void run() {
for(int i=0;i<1000;i++) {//循环
System.out.println("一斤黄金");
}
}
}
//创建MyRunnable2类并实现接口Runnable
class MyRunnable2 implements Runnable {
public void run() {
for(int i=0;i<1000;i++) {//循环
System.out.println("两斤翡翠");
}
}
}

//==================================================================================

package seday08.thread;
/**
* @author xingsir
* 使用匿名内部类完成两种线程的创建方式
* 好处:执行一次,代码简易。
*/
public class ThreadDemo3 {
//方式一Thread
public static void main(String[] args) {
Thread t1=new Thread() {
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("一斤黄金");
}
}
};
//方式二Runnable
Runnable r1= new Runnable() {
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("两斤翡翠");
}
}
};
Thread t2 =new Thread(r1);
t1.start();
t2.start();
}

}

posted on 2019-12-18 14:33  宗策  阅读(518)  评论(0编辑  收藏  举报