多线程机制
线程的概念
Runnable接口与Thread类
线程的控制与调度
线程的同步机制
线程的概念
程序、进程和线程
线程的生命周期与线程的状态
创建、可运行、运行中、阻塞、死亡
日常生活中的程序、进程和线程
程序:每学期的课程表
进程:每学期的教学活动
线程:每门课的教学过程
Runnable接口与Thread类
Runnable接口
Thread类
继承Thread类创建线程
实现Runnable接口创建线程
两种创建线程方法的比较
线程组
继承Thread类创建线程
public class Thread1 extends Thread
{
int k=0;
public Thread1(String name,int k)
{
super(name);
= k;
}
public void run() //覆盖run方法的线程体
{
int i = k;
();
(getName()+": ");
while (i<50)
{
(i+" ");
i+=2;
}
(getName() +" end!");
}
public static void main (String args[])
{
Thread1 t1 = new Thread1("Thread1",1);
//创建线程对象
Thread1 t2 = new Thread1("Thread2",2);
(); //启动执行线程
(); ("activeCount="+());
}
}
D:\myjava>javac
D:\myjava>java Thread1
activeCount=3
Thread1: 1 3 5 7 9 11 13 15 17 19 21 23 25 27
Thread2: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 Thread2 end!
29 31 33 35 37 39 41 43 45 47 49 Thread1 end!
实现Runnable接口创建线程
public class Runnable1 implements Runnable
{ int k=0;
public Runnable1(int k)
{ = k;
}
public void run()
{ int i = k;
();
while (i<50)
{ (i+" ");
i+=2;
}
}
public static void main (String args[])
{
Runnable1 r1 = new Runnable1(1);
//创建具有线程体的目标对象
Runnable1 r2 = new Runnable1(2);
Thread t1=new Thread(r1);
//以目标对象创建线程
Thread t2=new Thread(r2);
();
();
}
}
D:\myjava>javac
D:\myjava>java Runnable1
1 3 5 7 9 11 13 15 17 19 21 23
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48
25 27 29 31 33 35 37 39 41 43 45 47 49
多线程机制 来自淘豆网m.daumloan.com转载请标明出处.