多线程
java的多线程的实现有有两种手段,一种是继续Thread类,另外一种是实现Runable接口
public class test extends Thread{ String name; public test(String name){ this.name=name; } public void run(){ for(int i=0; i<5;i++){ System.out.println(name+"运行" +i); } } public static void main(String[] args) { test t1=new test("a"); test t2=new test("b"); t1.start(); t2.start(); } }
public class test implements Runnable { String name; public test(String name){ this.name=name; } public void run(){ for(int i=0; i<5;i++){ System.out.println(name+"运行" +i); } } public static void main(String[] args) { test t1=new test("a"); Thread demo=new Thread(t1); test t2=new test("b"); Thread demo1=new Thread(t2); demo.start(); demo1.start(); }
线程常用方法
1、sleep()
使当前线程(即调用该方法的线程)暂停执行一段时间,让其他线程有机会继续执行,但它并不释放对象锁。也就是说如果有synchronized同步快,其他线程仍然不能访问共享数据。注意该方法要捕捉异常。
yield()方法只会给相同优先级或者更高优先级的线程一个运行的机会。
2 、join()
join()方法使调用该方法的线程在此之前执行完毕,也就是等待该方法的线程执行完毕后再往下继续执行。注意该方法也需要捕捉异常。
3 interrupt():中断线程,被中断线程会抛InterruptedException

浙公网安备 33010602011771号