public class Thread02 implements Runnable {
public static void main(String[] args) {
Runnable r = new <strong>Thread02</strong>();
Thread t1 = new Thread(<strong>r</strong>, "t1");
/**
* Thread源码
* public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
*/
Thread t2 = new Thread(r, "t2");
t1.start(); // 启动线程t1,处于就绪状态,等待cpu
t2.start(); // 启动线程t2,处于就绪状态,等待cpu
t1.run(); // 主线程main调用对象t1的run方法
}
public void run() {
System.out.println("thread's name is "
+ Thread.currentThread().getName());
}
}
thread's name is t1 thread's name is main thread's name is t2
public class Thread03 extends Thread {
public static void main(String[] args) {
Thread03 t1 = new <strong>Thread03</strong>(); //不注意的情况下写成了Thread t1=new Thread() 注:Thread03此时就是一个线程了
t1.start();
}
public void run() {
System.out.println("thread's name is "
+ Thread.currentThread().getName());
}
}
public class Thread01 {
public static void main(String[] args) {
Thread thread=new Thread();
thread.start();//真正起作用 的是run()
/**而Thread中的run
* public void run() {
if (target != null) {
target.run();
}
}
所以自己创建的线程要重写run方法,把要执行的内容放到run()中,所以要实现接口或继承进而产生子类
*/
//创建线程的方式1 thread子类方式(继承)
Thread thread1=new Thread(){
public void run() {
while(true){
try {
Thread.sleep(500);//休息500毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
//Thread.currentThread()得到当前线程
System.out.println("线程1的名字是 "+Thread.currentThread().getName());
}
}
};
// thread1.start(); //不写 线程无法启动
//创建线程的方式2 runnable方式(实现) 推荐使用
Thread thread2=new Thread(new Runnable(){
public void run() {
while(true){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread2'name is "+Thread.currentThread().getName());
}
}});
// thread2.start();
//执行的是thread
new Thread(new Runnable(){
public void run() {
System.out.println("runnable "+Thread.currentThread().getName());
}}){
public void run() { //子类中的run方法覆盖父类中的run方法,这样就不会执行runnable
System.out.println("thread "+Thread.currentThread().getName());
}
}.start();
}
/***
* 在单个cpu中执行多线程很有可能降低执行效率而不是提高 一个人在不同地方做同一件事情
*/
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有