线程生命周期
线程的生命周期:新建状态、准备状态、运行状态、等待/阻塞状态、死亡状态
示意图:
定义、创建及运行线程
线程:
package threadrun; //定义一个实现Runnable接口的类
class Myrunable1 implements Runnable
{
public void run()
{
for(int i=0;i<=50;i++)
{
System.out.println("线程1");
}
}
}
//定义一个实现Runnable接口的类
class Myrunable2 implements Runnable
{
public void run()
{
for(int i=0;i<=50;i++)
{
System.out.println("线程2");
}
}
} public class thread1 {
public static void main(String arges[])
{
Myrunable1 m1=new Myrunable1();
Myrunable2 m2=new Myrunable2();
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
t1.start();
t2.start();
}
}
运行结果:
加一个让线程睡眠的方法
package threadrun; //定义一个实现Runnable接口的类
class Myrunable1 implements Runnable
{
public void run()
{
for(int i=0;i<=4;i++)
{
try {
Thread.sleep(50);//使用sleep方法使线程进入睡眠状态50毫秒
} catch (InterruptedException e) { e.printStackTrace();
}
System.out.println("线程1");
}
}
}
//定义一个实现Runnable接口的类
class Myrunable2 implements Runnable
{
public void run()
{
for(int i=0;i<=4;i++)
{
try {
Thread.sleep(50);//使用sleep方法使线程进入睡眠状态50毫秒
} catch (InterruptedException e) { e.printStackTrace();
}
System.out.println("线程2");
}
}
} public class thread1 {
public static void main(String arges[])
{
Myrunable1 m1=new Myrunable1();
Myrunable2 m2=new Myrunable2();
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
t1.start();
t2.start();
}
}
运行结果:
设置线程优先级
package threadrun; //定义一个实现Runnable接口的类
class Myrunable1 implements Runnable
{
public void run()
{
for(int i=0;i<=4;i++)
{
System.out.println("线程1");
}
}
}
//定义一个实现Runnable接口的类
class Myrunable2 implements Runnable
{
public void run()
{
for(int i=0;i<=4;i++)
{
System.out.println("线程2");
}
}
} public class thread1 {
public static void main(String arges[])
{
Myrunable1 m1=new Myrunable1();
Myrunable2 m2=new Myrunable2();
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
//设置线程优先级
t1.setPriority(Thread.MAX_PRIORITY);//最高优先级
t2.setPriority(Thread.MAX_PRIORITY);//最低优先级
t1.start();
t2.start();
}
}
线程优先级
运行结果:
package threadrun; //定义一个实现Runnable接口的类
class Myrunable1 implements Runnable
{
public void run()
{
for(int i=0;i<=4;i++)
{
try {
Thread.sleep(50);//使用sleep方法使线程进入睡眠状态50毫秒
} catch (InterruptedException e) { e.printStackTrace();
}
System.out.println("线程1");
}
}
}
//定义一个实现Runnable接口的类
class Myrunable2 implements Runnable
{
public void run()
{
for(int i=0;i<=4;i++)
{
try {
Thread.sleep(50);//使用sleep方法使线程进入睡眠状态50毫秒
} catch (InterruptedException e) { e.printStackTrace();
}
System.out.println("线程2");
}
}
} public class thread1 {
public static void main(String arges[])
{
Myrunable1 m1=new Myrunable1();
Myrunable2 m2=new Myrunable2();
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
//设置线程优先级
t1.setPriority(Thread.MAX_PRIORITY);//最高优先级
t2.setPriority(Thread.MAX_PRIORITY);//最低优先级
t1.start();
t2.start();
}
}
带睡眠方法的线程优先级
运行结果: