java 线程

Thread笔记
一、 简单的多线程例子
class Ticket extends Thread
{
private int tickets = 100;

public void run() {
while(true) {
if(tickets > 0) {
System.out.println(Thread.currentThread().getName() + "...sales_" + tickets--);
}
}
}
}

public class ThreadDemo_1 
{
public static void main(String[] args)
{
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
Ticket t3 = new Ticket();
Ticket t4 = new Ticket();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

上面的程序将会出现每个线程都卖出100张票的问题
而解决问题的方法有两种:
第一种:在tickets前面加上static使其成为静态的,private static int tickets = 100;
第二种:实现Runnable接口创建线程
class Ticket implements Runnable
{
private int tickets = 100;
public void run() {
while(true) {
if(tickets > 0) {
System.out.println(Thread.currentThread().getName() + "...sales_" + tickets--);
}
}
}
}

public class ThreadDemo_3
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}

使用实现接口的方式创建线程的好处很多,最重要的是它可以实现线程的同时,继承其它的类,实现多继承的效果。以后的程序中会以实现接口的方式为主。
二、 上面的程序虽然解决了问题,但还有隐藏的问题存在。例如,如果在判断语句if(tickets > 0)之后,加上sleep()方法则会出现有线程卖出票号为负的问题。原因在此不做解释,分析可得。
class Ticket implements Runnable
{
private int tickets = 100;

public void run() {
while(true) {
if(tickets > 0) {
try {
Thread.sleep(10);
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...sales_" + tickets--);
}
}
}
}

程序运行的结果(最后面):
Thread-0...sales_0
Thread-3...sales_-1
Thread-1...sales_-2
三、 为解决上述问题,修改类如下:
class Ticket implements Runnable
{
private int tickets = 100;
Object object = new Object();
public void run() {
while(true) {
synchronized(object) {
if(tickets > 0) {
try {
Thread.sleep(10);
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...sales_" + tickets--);
}
}
}
}
}

锁定成员变量,使得在一段时间内只有一个线程能够访问到共用的成员变量。
第二种锁定方法:不能直接锁定run()方法,要不然只有第一个线程能够访问run方法,而且里面是无限循环,也就是说只有一个线程在卖票,而其余的线程没能起到相应的作用。
class Ticket implements Runnable
{
private int tickets = 100;
Object object = new Object();
public void run() {
while(true) {
show();
}
}
public synchronized void show() {
if(tickets > 0) {
try {
Thread.sleep(10);
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...sales_" + tickets--);
}
}
}

四、 由上述程序我们可以看到,synchronized()方法的参数(即锁)是任一对象,那我们对方法进行锁定的时候,没有指明锁是哪个,那么默认的锁是哪个呢?默认的锁是this,下面我们使用程序进行验证。
class Ticket implements Runnable
{
private int tickets = 100;
Object obj = new Object();
boolean flat = true;
public void run() {
if(flat) {
while(true) {
synchronized(obj) {
if(tickets > 0) {
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName() + "...sales..." + tickets--);
}
}
}
} else { show(); }
}
public synchronized void show() {
while(true) {
if(tickets > 0) {
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName() + "...show_" + tickets--);
}
}
}
}

public class ThisLockDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(10);}catch (Exception e){}
t.flat = false;
t2.start();
}
}

使用两个线程进行售票,但将两个线程分开进行执行,当不使用默认锁的时候,我们可以得到的运行结果是:
Thread-1...show_3
Thread-0...sales...2
Thread-1...show_1
Thread-0...sales...0
可以看出其售出了0号票,可以我们已经加锁了,怎么会这样呢,因为使用的是两个不同的锁,所以会出现问题,如果我们将,非默认的锁改成this则会得到输出结果为:
Thread-1...show_4
Thread-1...show_3
Thread-1...show_2
Thread-1...show_1
没有出现0号票,使用的是同一个锁,所以证明,没有指定锁对象的时候,使用的是this对象。
五、 如果同步的方法是静态的,那么它使用的锁对象又是谁呢?由于静态方法中,是没有this对象的,而只有一个类的字节码文件对象,因此我们猜此时的锁对象就是它的字节码文件对象,下面我们使用程序进行验证:
将Ticket类修改如下,使show()方法变成静态方法:
class Ticket implements Runnable
{
private static int tickets = 100;
boolean flat = true;
public void run() {
if(flat) {
while(true) {
synchronized(this) {
if(tickets > 0) {
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName() + "...sales..." + tickets--);
}
}
}
} else { show(); }
}
public static synchronized void show() {
while(true) {
if(tickets > 0) {
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName() + "...show_" + tickets--);
}
}
}
}

则我们得到程序的运行结果:
Thread-1...show_3
Thread-0...sales...2
Thread-1...show_1
Thread-0...sales...0
又出现了0号票,因此静态方法的锁对象不是this对象。下面验证其锁对象为方法所在类的字节码文件对象,此时我们将this修改为Thicket.class进行实验,得到运行结果:
Thread-0...sales...4
Thread-0...sales...3
Thread-0...sales...2
Thread-0...sales...1
由此可以验证,静态方法使用的锁对象是方法所在类的字节码文件对象。
六、 死锁程序
class Test implements Runnable
{
//定义布尔变量flag,对线程进行判断,让其执行相应的代码块
private boolean flag;
public Test(boolean flag) {
this.flag = flag;
}
//使用两个锁对象,对两个代码块都进行锁定,而且是相互锁定
public void run() {
//根据线程的布尔属性执行不同的代码块
//两个锁对象是相互嵌套的
if(flag) {
synchronized(DeadLockTest.locka) {
System.out.println("if locka");
synchronized(DeadLockTest.lockb) {
System.out.println("if lockb");
}
}
} else {
synchronized(DeadLockTest.lockb) {
System.out.println("else lockb");
synchronized(DeadLockTest.locka) {
System.out.println("else locka");
}
}
}
}
}

public class DeadLockTest 
{
static Object locka = new Object();
static Object lockb = new Object();
public static void main(String[] args)
{
//建立两个布尔属性不一样的线程,并启动
Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));
t1.start();
t2.start();
}
}

/******************************对死锁的程序要理解透彻**************************************/
七、 加锁使线程同步时要注意的三个条件
第一、 多个线程
第二、 操作同一对象
第三、 使用同一个锁
八、 线程间的通讯(设置一个人的属性读一个人)
class People
{
private String name;
private String sex;
boolean flag = false;
public synchronized void set(String name, String sex) {
if(flag)
try{this.wait();}catch(InterruptedException e) {}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out() {
if(!flag)
try{this.wait();}catch(InterruptedException e) {}
System.out.println(name + "..." + sex);
flag = false;
this.notify();
}
}

class Input implements Runnable
{
private People p;
public Input(People p) {
this.p = p;
}
int i = 0;
public void run() {
while(true) {
if(i == 0) {
p.set("nike","male");
} else {
p.set("丽丽","女");
}
i = (i+1)%2;
}
}
}

class Output implements Runnable
{
private People p;
public Output(People p) {
this.p = p;
}
public void run() {
while(true) {
p.out();
}
}
}


public class InputOutputDemo_2
{
public static void main(String[] args)
{
People p = new People();
new Thread(new Input(p)).start();
new Thread(new Output(p)).start();
}
}

九、 当出现两个以上的生产者和消费者时,我们需要使用while进行判断,且使用notifyAll()唤醒所有线程
class Product
{
private String name = "";
private int count = 0;
boolean flag = false;
public synchronized void set(String name) {
while(flag) //*********
try{this.wait();}catch(InterruptedException e) {}
this.name = name + "..." + count++;
System.out.println(Thread.currentThread().getName() + "...生产者" + this.name);
flag = true;
this.notifyAll();
}
public synchronized void out() {
while(!flag)//********
try{this.wait();}catch(InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + "...消费者......" + this.name);
flag = false;
this.notifyAll();
}
}

class Producer implements Runnable
{
private Product pro;
public Producer(Product pro) {
this.pro = pro;
}
public void run() {
while(true) {
pro.set("商品");
}
}
}

class Consumer implements Runnable
{
private Product pro;
public Consumer(Product pro) {
this.pro = pro;
}
public void run() {
while(true) {
pro.out();
}
}
}

class ProducerConsumerTest  
{
public static void main(String[] args)
{
Product pro = new Product();
Producer p = new Producer(pro);
Consumer c = new Consumer(pro);
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}

十、 线程间的通信、
JDK1.5的新特性:提供了多线程升级解决方案,将同步synchronized替换成现实Lock操作,将Object中的wait,notify,notifyAll等方法替换成Condition对象,该对象可以通过Lock锁进行获取,可以实现只唤醒对方的操作,不过解锁的动作必须要完成,也就是用finally包括。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值