package test;
/**
* @author 小小小白白白白
*/
public class Cpu {
public static void main(String[] args) {
Cat cat = new Cat();
//启动线程
cat.start();
Dog dog = new Dog();
//因为dog是实现了Runnable接口的,无法直接调用start方法
//dog.start();
Thread thread = new Thread(dog);
//这里设计到代理模式
thread.start();
//这里执行run只是执行一个普通方法,没有开启线程
//它会执行完run方法之后再向下执行
//真正实现多线程的是start0(),而不是run
//start0()是本地方法由JVM机调用
cat.run();
//当main线程启动一个子线程时,主线程不会阻塞会继续执行
//这时主线程和子线程是交替执行的
//可以在终端页面输入jconsole来查看线程
System.out.println("主线程继续执行"+Thread.currentThread().getName());
for(int i=0; i<40;i++){
System.out.println("主线程"+i);
//休眠一秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 一个类创建线程的两种方式
*
* 1 继承了Thread,通过重写run方法来实现自己的功能
*/
class Cat extends Thread{
@Override
public void run() {
int amount=0;
while (true) {
System.out.println("我是加菲猫"+(++amount));
try {
//让线程休眠一秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(amount == 60){
break;
}
}
}
}
/**
* 2 实现了Runnable接口,重写run方法
*/
class Dog implements Runnable{
@Override
public void run() {
int amount=0;
while (true) {
System.out.println("我是欧弟"+(++amount));
try {
//让线程休眠一秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(amount == 60){
break;
}
}
}
}
线程基础(实现线程的两种方式)
最新推荐文章于 2022-11-09 20:55:38 发布