1.thread是多线程,凡是thread的子类都是一个线程.
2.thread必须调用start方法进开启线程,不能直接调用Runnable中的run方法,因为直接调用run方法没有创建新的线程,就不是多线程.
调用start方法的同时,JVM自动调用run方法.
3.thread的步骤
1.创建一个Runnable的实现类,实现里面的run方法,将线程中需要执行的方法放到run中.
2.创建该Runnable对象的Thread
3.调用start方法,开启线程.
4.thread方法
1.static currentThread获取当前线程
Thread[thread-0,5,main]
thread-0:线程名字
5:线程优先级
2.currentThread.getName()获取线程的名字
5.sleep(毫秒) 让线程休眠
6.synchronized同步锁,如果出现多个线程共享同一个数据时,将共享数据用同步锁进行上锁,
创建Runnable实现类
public class RunnableTest implements Runnable{ //定义成员变量 private int tickets = 100; @Override public void run() { while(true){ synchronized (this) {//同步锁 if(tickets>0){ try { Thread.sleep(100); } catch (Exception e) { // TODO: handle exception } System.out.println(Thread.currentThread().getName()+"卖出票数:"+tickets--); } } } } }
public class ThreadTicket { public static void main(String[] args) { //1.创建RunnableTest对象 RunnableTest runnableTest = new RunnableTest(); //2.创建thread对象 Thread thread1 = new Thread(runnableTest); Thread thread2 = new Thread(runnableTest); Thread thread3 = new Thread(runnableTest); //3.开启线程 thread1.start(); thread2.start(); thread3.start(); } }