0
点赞
收藏
分享

微信扫一扫

线程知识点总结

juneyale 2022-04-13 阅读 38

现在我们进入正题,实现线程的第一个方法:

     在Java中java.lang.Thread 这个类表示线程,一个类可以继承Thread并重写run方法来实现一个线程,代码如下:


public class Demo001 extends Thread{
 
    @Override
    public void run() {

          System.out.println(Thread.currentThread().getName());

      }
 }

第二个方法 :实现Runnable 接口
     通过继承Thread来实现线程虽然比较简单,但Java中只支持单继承,每个类最多只能有一个父类,如果类已经有父类了,就不能再继承Thread,这时,可以通过实现java.lang.Runnable接口来实现线程。Runnable接口的定义很简单,只有一个run方法,如下所示:

 

public class Demo001 implements Runnable {

    @Override
    public void run() {
       
          System.out.println(Thread.currentThread().getName());
                
      }
}


无论是通过继承Thead还是实现Runnable接口来创建线程,启动线程都是调用start方法,
还需要创建一个Thread对象来调用Start方法。;

下面我们演示一个案例,调用三个线程来出售100张电影票:

package thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyRunnable implements Runnable {
    private int tickets = 100;
    private Object obj = new Object();
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "开始售第:" + tickets + "张票");
                    tickets--;
                } else {
                    break;
                }
            } finally {
                lock.unlock();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
package thread;

public class MyRunnableDemo {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();

        Thread t1 = new Thread(mr,"第一窗口");
        Thread t2 = new Thread(mr,"第二窗口");
        Thread t3 = new Thread(mr,"第三窗口");

        t1.start();
        t2.start();
        t3.start();

    }
}

输出结果(由于结果篇幅过长,这里仅展示部分):

 

举报

相关推荐

0 条评论