一、线程与进程概述
Java的线程是通过java.lang.Tread类来实现的,通过重写run()方法
二、实现线程两种方法:
1、继承Thread类
public class Demo03 {
public static void main(String[] args) {
Thread t1=new MyThread();
t1.setName("线程1");
t1.start();
Thread t2=new MyThread();
t2.setName("线程2");
t2.start();
String str=Thread.currentThread().getName();
for (int i = 0; i <100 ; i++) {
System.out.println("........."+str+"........."+i);
}
}
}
class MyThread extends Thread{
@Override
public void run() {
String str=Thread.currentThread().getName();
for (int i = 0; i <100 ; i++) {
System.out.println("....MyThread......run()..."+str+"......."+i);
}
}
}
2、实现Runnable接口
public class Demo02 {
public static void main(String[] args) {
Runnable3 r=new Runnable3();
Thread t1=new Thread(r);
Thread t2=new Thread(r);
t1.start();
t2.start();
for (int i = 0; i < 100; i++) {
String str=Thread.currentThread().getName();
System.out.println("......Demo02......"+str+"......"+i);
}
}
}
class Runnable3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
String str=Thread.currentThread().getName();
System.out.println("....Runnable3.. ."+str+"....."+i);
}
}
}
三、线程状态及生命周期
public class Demo04 {
public static void main(String[] args) {
MyThread4 mt=new MyThread4();
mt.start();
}
}
class MyThread4 extends Thread{
@Override
public void run() {
for (int i = 0; i <60 ; i++) {
try {
// 阻塞
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i="+i+"\t\t\t"+new Date());
if(i==10){
break;
}
}
}
}
四、线程优先级
优先级高代表cpu会给你多分配点运行时间,优先级用数字表示,范围1-10,主线程默认优先级为5
方法:
.sleep(毫秒数);时间结束,自动唤醒
.wait();需要唤醒