【Java总结-线程】Java多线程的使用

来源:互联网 发布:域名投资骗局 编辑:程序博客网 时间:2024/05/17 06:40

创建线程的两种方式

继承Thread类

  • 定义一个类继承Thread类
  • 子类中重写Thread类中的run方法
  • 创建Thread子类的对象,就是创建了线程对象
  • 调用线程对象的start方法,启动线程,会自动调用run方法
public class TestThread extends Thread {    public static void main(String[] args) {        TestThread tt = new TestThread();        tt.start();    }    //重写run方法    public void run() {        System.out.println("run");    }}

实现Runnable接口

  • 自已子类实现Runnable接口
  • 重写接口中的run方法
  • 通过Thread含参构造器创建线程对象
  • 将Runnable接口子类的对象作为实参传递
  • 调用Thread类的start方法,开启线程
public class TestThread {    public static void main(String[] args) {        T t = new T();        Thread tt = new Thread(t);        tt.start();    }}class T implements Runnable {    @Override    public void run() {        System.out.println("run");    }}

应该多使用Runnable接口实现多线程,可以实现多继承

String getName();返回当前线程void setName(String name);//设置线程名字static currentThread();//返回当前线程
setPriority(int new);//改变线程的优先级getPriority()返回线程的优先级
Thread.sleep(10);//让线程睡10秒,阻塞

线程同步

synchroized(对象) {    //需要同步的代码}
public synchroinized void show(String name) {    ...}

线程通讯

wait();//让当前线程等待notify();//唤醒线程notifyAll();//唤醒正在排队的所有线程
0 0
原创粉丝点击