JAVA基础(四)

来源:互联网 发布:sql设置取值范围 编辑:程序博客网 时间:2024/05/16 08:49

线程

线程的创建的两种方法

继承Thread 方法

public class Test {public static void main(String[] args) {//创建一个线程FirstThread ft = new FirstThread();//启动这个线程ft.start();while(true){System.out.println("789");}}}public class FirstThread extends Thread {public void run(){while (true){System.out.println("123");}}}

重写run方法

public class Test {public static void main(String[] args) {//创建一个线程,心接口的方式创建的Runnable线程对象,需要通过构造Thread来创建线程SecondThread st = new SecondThread();//通过构造Thread来创建线程Thread ss = new Thread(st); //启动这个线程ss.start();System.out.println("592");}}public class SecondThread implements Runnable {public void run() {System.out.println(369);}}

在实现接口Runnable接口时,Runable中有一个run的方法需要实现,线程执行时,执行的是线程run方法,启动线程调用的是start方法而不是run方法

常用的方法

getpriority()和setpriority()方法

是一个设置或获取线程的数值优先级的功能 ,他获得的参数越大优先级越低

getState()方法

是用来获取线程当前状态的

sleep(iong maillis)方法

可以有使 在运行的线程休眠

Thread.sleep(50);
yield()方法

让出CPU,让CPU去执行另外的线程,在使用这种方法时,不是这个线程不执行了,是在执行过程中,他执行一次,让出一些时间让另外的线程去执行

isAlive()方法

是用来查看某个线程是否处于活动状态

join()方法

在一个简单的程序中,有两个线程存在,如果一个线程调用另一个线程的join方法,要等被调join方法这个程序执行完之后,另外一个线程才能被执行






原创粉丝点击