最近多java多线程的学习比较感兴趣,所以在图书馆找到了一本好书能够带我进行多线程的基础学习。之前在网上找的教程,学习了一点但是感觉还是没有入门,一些比较重要的知识很多文章都没有仔细讲解。所以现在是重新开始学习java多线程。
进程和线程的概念就不在这里说了。
1.实现多线程方式有两种,一种是继承Thread,另一种是实现Runnable接口。
现在主要是推荐实现Runnable接口,因为java的机制是不支持多继承。
package learnThread;
public class MyThread8 extends Thread
{
public void run()
{
super.run();
System.out.println("测试线程 ");
}
public static void main(String[] args)
{
MyThread8 m=new MyThread8();
m.start();
System.out.println("运行结束");
}
}
package learnThread;
public class myThread implements Runnable {
public void run()
{
System.out.println("测试线程");
}
public static void main(String[] args)
{
Runnable runable=new myThread();
Thread thread=new Thread(runable);
thread.start();
System.out.println("运行结束");
}
}
搜狗截图18年03月27日2027_1.png
实现的结果都没什么差别。
使用多线程技术,代码的运行结果与代码的执行顺序或者调用顺序是无关的。
Thread.java类中的start()方法通知“线程规划器”此线程已经准备就绪,等待调用线程对象的run()方法。这个过程就是让系统安排一个时间来调用Thread中的run方法,也就是使线程得到运行。启动线程,具有异步执行的效果。
currentThread():可返回代码段正在被哪个线程调用的信息
isAlive():判断当前的线程是否处于活动状态
sleep():指定的毫秒数内让当前线程休眠
getid():取得线程的唯一标识
停止线程
java中有三种方法可以终止正在运行的线程
1.使用中途退出标志,使线程正常退出,也就是当run方法完成后线程终止。
2.使用stop方法强制终止线程,但是不推荐这个方法,因为stop和suspend以及resume一样,都是过期作废的方法,它们可能会残生不可预料的效果
3.使用interrupt方法中断线程。
能停止的线程------异常法
package learnThread;
//停止线程
public class myThread5 extends Thread
{
public void run()
{
super.run();
try {
for(int i=0;i<500000;i++)
{
if(this.isInterrupted())
{
System.out.println("已经停止了,能退出了");
throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
System.out.println("我在for下面");
}
catch (InterruptedException e) {
System.out.println("进行run()方法中的catch");
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException
{
try
{
myThread5 thread=new myThread5();
thread.start();
Thread.sleep(2000);
thread.interrupt();
}
catch(InterruptedException e)
{
System.out.println("catch main");
e.printStackTrace();
}
}
}
睡眠法
package learnThread;
//停止线程
public class myThread6 extends Thread
{
public void run()
{
super.run();
try
{
System.out.println("run begin");
Thread.sleep(20000);
System.out.println("run end");
}
catch(InterruptedException e)
{
System.out.println("在沉睡中停止线程 "+this.isInterrupted());
e.printStackTrace();
}
}
public static void main(String[] args)
{
try
{
myThread6 thread=new myThread6();
thread.start();
Thread.sleep(200);
thread.interrupt();
}
catch(InterruptedException e)
{
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end");
}
}
网友评论