1.线程启动(start)
这是作为多线程操作中最基本的标志了。当一个线程被创建,无疑只有当它启动了才能起到效果。我们重写了run方法后,用Thread类中的start方法启动。
public class TestStart implements Runnable{
//重写run方法
public void run(){
System.out.println("线程成功启动!");
}
public static void main(String[] args){
TestStart test=new TestStart();//创建实现类对象
Thread thread=new Thread(test);//创建线程类对象,并向构造器抛入实现类对象
thread.start();//启动线程
}
}
2.线程礼让(yield)
顾名思义,该操作是让线程从运行态主动退出,转为就绪态。注意,这里是转为就绪态,而不是停止或阻塞,因此“礼让“”有个特点是我让了,但我还能和你们公平抢夺。
public class TestYield {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyYiled a=new MyYiled();
MyYiled b=new MyYiled();
//启动两个线程
new Thread(a).start();
new Thread(b).start();
}
}
class MyYiled implements Runnable{
public void run() {
System.out.println(Thread.currentThread()+"线程开始执行");
Thread.yield();//第一个被执行的线程进行礼让,重新让cpu分配时间片
System.out.println(Thread.currentThread()+"线程停止执行");
}
}
3.线程停止(stop)
4.线程优先级(priority)
在多线程中,同步是很重要的概念,与线程安全紧密相连。同步,通俗来讲就是当多个线程在操作同一个资源时,可以让他们排好队,一个一个来。而这时,优先级就是让我们人为去设置线程取得资源的次序。
(1)设置优先级(setpriority)
设置优先级往往说在线程启动前,创建了一个线程对象后,由线程对象去调用该方法。
优先级范围是从0~10。优先级数依次增高,10是最大的优先权。在未设置的情况下,线程级 默认为5,公平抢夺。
public class TestPriority implements Runnable{
public void run()
{
System.out.println(Thread.currentThread().getName()+" "+Thread.currentThread().getPriority());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+Thread.currentThread().getPriority());
TestPriority t1=new TestPriority();
TestPriority t2=new TestPriority();
TestPriority t3=new TestPriority();
TestPriority t4=new TestPriority();
TestPriority t5=new TestPriority();
Thread thread1=new Thread(t1);
Thread thread2=new Thread(t2);
Thread thread3=new Thread(t3);
Thread thread4=new Thread(t4);
Thread thread5=new Thread(t5);
thread1.setPriority(1);
thread1.start();
thread2.setPriority(2);
thread2.start();
thread3.setPriority(Thread.MAX_PRIORITY);
thread3.start();
thread4.setPriority(5);
thread4.start();
thread5.setPriority(6);
thread5.start();
}
}
(2)获取优先级(getpriority)
即查看线程优先级。方法为Thread类自带的getPriority()方法。