多线程-Thread常用方法

Thread implements Runnable

常用方法

static

Thread.currentThread()

  setName(String name);

  getName()

 

yield()

  yield()方法:暂停当前正在执行的线程对象,并执行其他线程。

        运行->就绪

        使用方法 : 在run()中直接使用

join()

  在主线程中调用线程th1的join,然后主线程阻塞,让渡给th1,th1执行完成之后回到主线程

        使用方法 线程外部调用

 1 class test {
 2 
 3 
 4     public static void main(String[] args) throws InterruptedException {
 5         MyThread th1 = new MyThread();
 6         th1.start();
 7         th1.setName("线程1");
 8         Thread.currentThread().setName("主线程");
 9 
10         for (int i = 0; i < 100; i++) {
11             if (i % 2 == 0) {
12                 System.out.println(Thread.currentThread().getName() + ";" + i);
13             }
14             if(i==20){
15                 th1.join();
16             }
17 
18 
19         }
20 
21 
22     }
23 }

 sleep()//定义在Thread中  任何地方可以使用 不会释放锁

  sleep(long millis) 

    使用:run()内调用



wait() 一定要在同步使用 会释放锁
notifyAll()
定义在object中
/**
 * @author lisa
 * @create 2020-08-10-21:14
 */
public class RunnableTest {
    public static void main(String[] args) {
        runnable();

    }
    static void runnable(){

        Runnable r=new Runnable() {
            window window=new window();
            int ticket=100;
            @Override
            public void run() {
                if (ticket > 0) {
                    while (true) {
                        synchronized (this) {
                            notifyAll();//必须与syn绑定的锁对象一致也就是说如果Thread.class 就不能直接wait() 而且必须在同步代码块中使用
//这三个方法调用者必须是同步监视器lock
if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票"); ticket--; try{ Thread.sleep(100); } catch (Exception e){ e.printStackTrace(); } } else { break; } try { wait();//会释放同步监视器 } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; Thread th1=new Thread(r); Thread th2=new Thread(r); Thread th3=new Thread(r); th1.start(); th2.start(); th3.start(); } }

 

       

 

posted on 2020-08-10 18:45  落华12580  阅读(159)  评论(0)    收藏  举报

导航