java 线程

第一讲(线程基本概念及其方法)

package com.thread;

public class ThreadTest01 {
public static void main(String[] args) {
	Runner1 r = new Runner1();
	Thread t = new Thread(r);
	t.start();//就绪,cpu调度后才能开始运行
	/**
	 * 如果没有使用thread这个类的话,那么不会有另外的线程,只有一条线程,这叫方法的调用;
	 * 如果不用thread,直接使用的是r.run();那么还是一条线程,并没有开启新的线程;
	 */
	for (int i = 0; i < 100; i++) {
		System.out.println("main"+i);
	}
}
}
class Runner1 implements Runnable{
	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println("runnable"+i);
		}
	}
}

调用start后,并没有直接开始执行,cpu调度后开始执行

1.当线程终止后,便进入了“死”状态

2.优先级值cpu并不是先运行那个线程,先后顺序根据start()的执行先后顺序而定的,所谓的优先级,获得cpu的执行时间越多,而不是运行时间,一定要区分

第二讲(sleep以及停止线程)

package com.thread;

import java.util.Date;

public class ThreadTest02 {
	public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
	Thread.sleep(10000);//在哪个线程中写入就代表着那个线程睡眠
} catch (InterruptedException e) {
}
thread.interrupt();//睡着后打断睡眠状态这算是结束线程的一种方式;只是打断sleep,如果要结束线程就在catch后retrun
	}
}

class MyThread extends Thread {
	@Override
	public void run() {
		while (true) {
			System.out.println(new Date());
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				//InterruptedException 是线程在睡眠被打断后抛出的异常
				return;//抛出的异常InterruptedException 结束线程
				
			}
		}
	}
}
/**
 * 结束线程的正确想法,定义一个flag来控制run的结束;
 */
class MyThread2 extends Thread {
	boolean flag = true;
	@Override
	public void run() {
		while (flag) {
			System.out.println(new Date());
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				return ;
			}
		}
	}
}

第三讲(join方法)

package com.thread;

public class ThreadTest03 {
 public static void main(String[] args) {
   MyThread3 thread = new MyThread3("t1");
    thread.start();
    try {
	thread.join();//将其线程合并入当前线程中,相当于就变成了方法调用;
 } catch (InterruptedException e) {
     }
    for (int i = 0; i < 10; i++) {
	System.out.println("此处是main线程");
  }
	}
}

class MyThread3 extends Thread {
	MyThread3(String s){super(s);}
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("当前线程:"+getName());
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				return ;
			}
		}
	}
}

第四讲(yield方法)

package com.thread;

public class ThreadTest04 {
 public static void main(String[] args) {
   MyThread4 thread1 = new MyThread4("t1");
   MyThread4 thread2= new MyThread4("t2");
   thread1.start();
   thread2.start();
	}
}
class MyThread4 extends Thread {
	MyThread4(String s){super(s);}
	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(getName()+":"+i);
			if(i%10==0){
				yield();//暂时让出cpu让其他线程执行,但不是一直让出;
			}
		}
	}
}

第五讲(线程优先级)

package com.thread;

public class ThreadTest05 {
 public static void main(String[] args) {
   MyThread5 thread1 = new MyThread5();
   MyThread6 thread2 = new MyThread6();
   thread1.setPriority(Thread.NORM_PRIORITY+3);//优先级越高,得到的cpu运行时间片越多;
   thread1.start();
   thread2.start();
	}
}
class MyThread5 extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("t1"+":"+i);
		}
	}
}
class MyThread6 extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("=======t2"+":"+i);
		}
	}
}

第六讲(线程同步)

① (银行存钱问题锁定当前执行方法)

package com.thread;
public class TestSync implements Runnable {
  Timer timer = new Timer();
  public static void main(String[] args) {
    TestSync test = new TestSync();
    Thread t1 = new Thread(test);
    Thread t2 = new Thread(test);
    t1.setName("t1"); 
    t2.setName("t2");
    t1.start(); 
    t2.start();
  }
  public void run(){
    timer.add(Thread.currentThread().getName());
  }
}

class Timer{
  private static int num = 0;
  //如果不锁定的话,在睡眠一秒后,两个线程都在执行add那么num都变成了2
 //锁定的意思为锁定当前的程序语句块
  public synchronized void add(String name){ 
      //synchronized (this) {
        num ++;
        try {Thread.sleep(1);} 
        catch (InterruptedException e) {}
        System.out.println(name+", 你是第"+num+"个使用timer的线程");
      //}
  }
}
 

② 死锁现象

package com.thread;

public class  TestDeadLock  implements Runnable {
    public int flag = 1;
    static Object o1 = new Object(), o2 = new Object();
    public void run() {
    System.out.println("flag=" + flag);
        if(flag == 1) {
            synchronized(o1) {
                //下面的synchronized块中必须在上面拿到o1的锁才能执行,如果o1被锁定,那么下面的语句块
                //就不能执行了,当它拿到o1的锁后,别的线程就不能访问o1了,
                //对类的锁定方法是synchronized(TestDeadLock.class)锁定类
                 try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(o2) {
                    System.out.println("1");    
                }
            }
        }
        if(flag == 0) {
            synchronized(o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(o1) {
                    System.out.println("0");
                }
            }
        }
    }    
    public static void main(String[] args) {
        TestDeadLock td1 = new TestDeadLock();
        TestDeadLock td2 = new TestDeadLock();
        td1.flag = 1;
        td2.flag = 0;
        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);
        t1.start();
        t2.start();
        
    }
}
③ 死锁现象(synchronized讲解)

synchronized 详解一

synchronized 详解二


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值