一.Thread类
1.1 定义:Thread是java.lang中的一员,是创建,调用,设计线程的重要工具类,正是通过它,使得我们可以实现多线程的效果;
1.2 调用方法:
1.2.1创建方法
- 继承 Thread, 重写 run:
class MyTread extends Thread{ public void run(){ while(true){ System.out.println("Hello MYTread!!!"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } public class thread { public static void main(String[] args) throws InterruptedException { Thread t = new MyTread(); //创建一个线程 t.start(); while (true){ System.out.println("hello main"); Thread.sleep(1000); } } } - 实现 Runnable, 重写 run:
class MyRunnable implements Runnable{ @Override public void run() { while(true){ System.out.println("hello Runnble"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } public class Demo2 { public static void main(String[] args) throws InterruptedException { Runnable runnable = new MyRunnable(); Thread t1 =new Thread(runnable); t1.start(); while (true){ System.out.println("hello main"); Thread.sleep(1000); } } } - 继承 Thread, 重写 run, 使用匿名内部类
public class Demo3 { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(){ @Override public void run() { while(true){ System.out.println("hello Runnble"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }; t.start(); while (true){ System.out.println("hello main"); Thread.sleep(1000); } } } - 实现 Runnable, 重写 run, 使用匿名内部类
public class Demo6 { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { while(true){ System.out.println("hello thread"); } } }; Thread t = new Thread(runnable); t.start(); } }
1.2.2Thread类的核心属性:
1:name 线程名称,在何时调用哪个线程发挥作用
2:isDaemon\setDaemon:守护线程(后台线程)的设置和检验,执行后台周期型任务。
3:isAlive:检验线程是否正在运行
1.2.2Thread类的开始和结束:
1.start:调用线程开始工作,运行线程内部操作
2.interrupt\isinterrupted:线程打断(终结);
1.2.3Thread类的join()方法:等待某个线程结束
1.2.4Thread类的sleep()方法:使线程进行休眠,单位ms;
1.3:线程安全
在多线程工作的过程中,由于CPU分时复用的特性,也就是调度是随机的,在执行任何指令的时候都有可能跳转任务,那么就可能出现多个线程中存在对同一个对象操作的情况,那么这个时候就回产生线程冲突,进而可能影响最总结果。
解决方法1:在一个线程结束后再调用另一个新线程,但,这种方法大大影响效率,所以不可取
解决方法2:使用synchronized(){}代码块来保证执行线程任务的不可插入性,也就是保证在执行线程任务a的时候,不允许跳转到其他的线程任务中去;

2001

被折叠的 条评论
为什么被折叠?



