1.线程
(1)线程是轻量级的进程
线程没有独立的地址空间(内存空间)
线程是由进程创建的(寄生在进程)
一个进程可以有多个线程
(2)线程有几种状态
a 新建状态(new)
b就绪状态(Rannable)
c运行状态(Running)
d阻塞状态(Blocked)
e死亡状态(Dead)
(3)在java中一个类要当作线程来使用有两种方法
1、继承Thread类,并重写run函数
2、实现runnable接口,并重写run函数
(某些情况下,一个类已经继承了某个父类就不能继承thread类了)
2.通过继承Thread类来实现建立线程实例
public classThread{
public static void main(String[] args){
Cat cat = new Cat();
cat.start();
}
}
class Cat extends Thread{
int times = 0;
public void run(){//重写run函数
while(true){
try{//休眠1秒
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
times++;
System.out.println("hello,word!" + times);
if(times == 10){
break;//退出线程
}
}
}
}
3.通过Runnable 接口来实现建立线程实例
public class Thread{
public static void main(String []args){
Dog dog = new Dog();
Thread t = new Thread(dog);//创建线程
t.start();//启动线程
}
}
class Dog implements Runnable{
public void run(){//重写run函数
int times = 0;
while(true){
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
times ++;
System.out.println("hello" + times);
if(times == 10){
break;
}
}
}
}
4.一个线程通过接收n来执行1+...+n得到和,
另一个线程每隔1秒输出一次hello world
public class Thread{
public static void mian(String[] args){
Pig pig = new Pig(10);
Bird bird = new Bird(10);
Thread t1 = new Thread(pig);//建立线程
Thread t2 = new Thread(bird);
t1.start();//启动线程
t2.start();
}
}
class Pig implements Runnable{//打印hello world
int n=0;
int times = 0;
public Pig(int n){
this.n=n;
}
public void run(){
while(true){
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStacktrace();
}
times++;
System.out.println("打印hello word");
if(times ==n){
break;
}
}
}
}
class Bird implements Runnable{//
int n=0;
int res=0;
int times = 0;
public Bird(int n){
this.n = n;
}
public void run(){
while(true){
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
res +=(++times);
System.out.println("结果是:"+res);
if(times==n){
System.out.println("最后结果是:"+res);
break;
}
}
}
}