java 线程学习(1)(一)

2014-11-24 03:14:05 · 作者: · 浏览: 0

import java.io.*;

/*

class Demo extends Thread

{

Demo(String name)

{

super(name);//给线程自定义命名

}

public void run()

{

for(int i=0;i<60;i++)

System.out.println(Thread.currentThread()+" "+this.getName()+" run-----"+i);//获取当前线程

}

}

class Test //发送端

{

public static void main(String[] args)

{

Demo d=new Demo("myThread");

d.start();//开启线程并执行该线程的run方法

//d.start();//当这个线程正在运行时,不能再启动

//d.run();//仅仅是对象调用方法,而线程创建了并没有运行

for(int i=0;i<60;i++)

System.out.println("hello world!!"+i);

}

}*/

/*synchrionized 块

class Ticket implements Runnable

{

private int ticket=1000;

Object obj=new Object();

public void run()

{

while(true)

{

synchronized(obj)

{

if(ticket>0)

{

System.out.println(Thread.currentThread().getName()+"---sale "+ticket--);

}

}

}

}

}

class Test

{

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();

}

}

*/

/* synchronized 方法

class Bank

{

private int sum;

//Object obj=new Object();

public synchronized void add(int n)

{

// synchronized(obj)

// {

sum=sum+n;

try{Thread.sleep(10);}catch(Exception e){}

System.out.println("sum--"+sum);

// }

}

}

class Cus implements Runnable

{

private Bank b=new Bank();

public void run()

{

for(int i=0;i<3;i++)

b.add(100);

}

}

class Test

{

public static void main(String[] args)

{

Cus c=new Cus();

Thread t1=new Thread(c);

Thread t2=new Thread(c);

t1.start();

t2.start();

}

}

*/

/*

//同步函数调用的哪一个锁呢?

//函数需要被对象调用,那么函数都有一个所属对象引用,就是this

//所以同步函数使用的锁是this 以下为验证

class Ticket implements Runnable

{

private int ticket=100;

Object obj=new Object();

boolean flag=true;

public void run()

{

if(flag)

{

while(true)

{

synchronized(this) //两个线程为同一个锁:安全 换成obj的话为两个锁:不完全

{

if(ticket>0)

{

try{Thread.sleep(10);}catch(Exception e){}

System.out.println(Thread.currentThread().getName()+"---sale "+ticket--);

}

}

}

}

else

while(true)

show();

}

public synchronized void show()

{

if(ticket>0)

{

try{Thread.sleep(10);}catch(Exception e){}

System.out.println(Thread.currentThread().getName()+"----show---"+ticket--);

}

}

}

class Test

{

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.flag=false;

t2.start();

}

}

*