标签:
class Thread {
private Runnable target;
Thread(Runnable target) {
this.target = target;
}
public void run() {
if (target != null) {
target.run();
}
}
public void start() {
run();
}
}
class PrintName extends Thread {
String name = null;
PrintName(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println( "name: " + this .name );
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
PrintName n1 = new PrintName( "张三");
PrintName n2 = new PrintName( "李四");
n1.start(); // 创建一个线程打印“张三”
n2.run(); // 利用主线程打印“李四"
}
}
/**
* 卖票程序,4个窗口同时卖同一种票,记录剩余票数量
*/
class TicketSale implements Runnable {
// 线程共享资源
private int tickets = 100;
public void run() {
// 重写Runnable的run()方法
while (tickets > 0) // 利用双重检查加锁方法
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
System.out.println(Thread. currentThread().getName() + " Sell :" + tickets --);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
TicketSale t = new TicketSale();
// 创建4个线程同时卖票
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 TicketSale implements Runnable {
// 共享资源
private int tickets = 100;
// 定义flag标志是两个卖票窗口,true为1号窗口,false为2号窗口
boolean flag = true;
public void run() {
if (flag) {
// 1号窗口开始卖票
while (tickets > 0)
{
// 使用同步代码块(锁必须一致,由于同步函数锁为this,所以这里必须是this)
Wait(10);
synchronized (this ) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + " Sell 1 :" + tickets--);
}
}
}
} else {
// 2号窗口开始卖票
while (tickets > 0) {
Wait(10);
// 使用同步函数(默认锁为this)
func();
}
}
}
synchronized void func() {
if (tickets > 0) {
System.out.println(Thread. currentThread().getName() + " Sell 2 :" + tickets--);
}
}
static void Wait( int time) {
try {
Thread.sleep(time );
} catch (InterruptedException e) {
}
}
}
public class ThreadSafe {
public static void main(String[] args) {
TicketSale t = new TicketSale();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
TicketSale.Wait(10);
t.flag = false;
t2.start();
}
}
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 卖票程序,两个窗口同时卖同一种票,记录剩余票数量
* 使用Lock方式同步
*/
class TicketSale implements Runnable {
// 多个对象共享资源
private static int tickets = 100;
// 定义买票窗口编号
private int num = 0;
public TicketSale( int num) {
super();
this.num = num;
}
// 定义锁,多个对象使用同一个锁
private final static Lock lock = new ReentrantLock();
public void run() {
while (tickets > 0) {
Wait(10);
lock.lock();
try {
func(num);
} finally {
// 释放锁是必须执行的
lock.unlock();
}
}
}
private void func( int num) {
if (tickets > 0) {
System.out.println(Thread. currentThread().getName() + " Sell " + num + " : " + tickets--);
}
}
static void Wait( int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {}
}
}
public class ThreadSafe {
public static void main(String[] args) {
new Thread( new TicketSale(0)).start();
new Thread( new TicketSale(1)).start();
new Thread( new TicketSale(2)).start();
new Thread( new TicketSale(3)).start();
}
}
class Locks {
static final Object LockA = new Object();
static final Object LockB = new Object();
}
class Demo implements Runnable {
private boolean flag = true;
Demo(boolean flag) {
this.flag = flag;
}
public void run() {
if (flag) {
synchronized (Locks. LockA) {
System. out.println("1. Get LockA!" );
synchronized (Locks.LockB) {
System. out.println("1. Get LockB!" );
}
}
} else {
synchronized (Locks. LockB) {
System.out.println("2. Get LockB!" );
synchronized (Locks.LockA) {
System.out.println("2. Get LockA!" );
}
}
}
}
}
public class ThreadDeadLock {
public static void main(String[] args) {
System.out.println("Hello World!");
Demo d1 = new Demo(true);
Demo d2 = new Demo(false);
new Thread(d1).start();
new Thread(d2).start();
}
}
/**
* 仅存一个产品的生产者消费者问题
* 有一群生产者在生产产品,并将这些产品提供给消费者去消费。为使生产者与消费者能够并发执行,在两者之间设置一个具有 n
* 个缓冲区的缓冲池,生产者将他所生产的产品放入一个缓冲区中;消费者可从一个缓冲区中取走产品去消费。尽管所有的生产者和消费者都是以异步方式运行,
* 但他们之间必须保持同步 ,即不允许消费者到一个空缓冲区去取产品;也不允许生产者向一个已装满产品且尚未被取走的缓冲区投放产品。
* 这里先仅讨论 n = 1 的情况,缓冲池用一个 flag 标志代替。
*
* 当生产者和消费者只有一个时:
* 1. 产品为临界资源,增加同步锁,避免出现消费的是早前生产的已经丢弃的产品。
* 2. 使用 wait 和 notify 方法进行线程通讯,避免出现连续多次生产和多次消费。
*
* 当生产者和消费者不止一个时:
* 3. 当一种角色全都等待时,另一种角色不同者容易发生循环等待 -唤醒,导致死锁,这时使用 notifyAll 方法代替 notify
* 方法释放全部等待的线程,避免死锁情况发生。
*/
class Resource {
private int num = 0; // 生产的产品编号,生产一个就加1,并打印。
boolean flag = false; // flag代表仓库,false代表无产品,true代表有产品。
public static final int MAX = 100;
public boolean isMax() {
return num >= MAX;
}
public synchronized void put() // 生产函数
{
while ( flag) // 如果有产品,则等待
{
System.out.println(Thread. currentThread().getName() + " wait!");
try {
wait();
} catch (InterruptedException e) {} // 暂时不做异常处理
// 唤醒后需要重新判断是否有产品,所以使用while
}
System.out.println(Thread. currentThread().getName() + "......生产..." + ++num );
flag = true;
// 使用notifyAll()方法避免同一种角色循环等待-唤醒照成死锁
notifyAll();
}
public synchronized void get() // 消费函数
{
// 同样地,可以用if-else代替while循环,避免未经判断得得到资源。
if (!flag) {
System.out.println(Thread. currentThread().getName() + " wait!");
try {
wait();
} catch (InterruptedException e) {}
} else {
System.out.println(Thread. currentThread().getName() + "......消费..." + num );
flag = false;
notifyAll();
}
}
}
class Producer implements Runnable {
private Resource r;
public Producer(Resource r) // 将公共的资源(仓库)传入构造函数
{
this.r = r;
}
public void run() {
while (! r.isMax()) {
r.put(); // 循环生产100次
}
}
}
class Consumer implements Runnable {
private Resource r;
public Consumer(Resource r) {
this.r = r;
}
public void run() {
// 循环消费100次,并消费掉所有库存
while (! r.isMax() || r. flag) {
r.get();
}
}
}
public class Thread_ProducerConsumer {
public static void main(String[] args) {
Resource r = new Resource();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
new Thread(c).start();
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 仅存一个产品的生产者消费者问题
* 使用Lock + Condition类方法实现
*/
class Resource {
private int num = 0; // 生产的产品编号,生产一个就加1,并打印。
boolean flag = false; // flag代表仓库,false代表无产品,true代表有产品。
public static final int MAX = 100;
private final Lock lock = new ReentrantLock();
private final Condition isEmpty = lock.newCondition();
private final Condition isFull = lock.newCondition();
public boolean isMax() {
return num >= MAX;
}
public void put() // 生产函数
{
lock.lock();
try {
while ( flag) // 如果有产品,则让生产者等待
{
System.out.println(Thread.currentThread().getName() + " wait!");
try {
// 让生产者等待
isEmpty.await();
} catch (InterruptedException e) {} // 暂时不做异常处理
// 唤醒后需要重新判断是否有产品,所以使用while
}
System.out.println(Thread. currentThread().getName() + "......生产..." + ++num );
flag = true;
// 唤醒消费者
isFull.signal();
} finally {
lock.unlock();
}
}
public void get() // 消费函数
{
lock.lock();
try {
while (! flag) {
System.out.println(Thread.currentThread().getName() + " wait!");
try {
isFull.await();
} catch (InterruptedException e) {}
}
System.out.println(Thread. currentThread().getName() + "......消费..." + num );
flag = false;
isEmpty.signal();
} finally {
lock.unlock();
}
}
}
class Producer implements Runnable {
private Resource r;
public Producer(Resource r) // 将公共的资源(仓库)传入构造函数
{
this.r = r;
}
public void run() {
while (! r.isMax()) {
r.put(); // 循环生产100次
}
}
}
class Consumer implements Runnable {
private Resource r;
public Consumer(Resource r) {
this.r = r;
}
public void run() {
// 循环消费100次,并消费掉所有库存
while (! r.isMax() || r. flag) {
r.get();
}
}
}
public class Thread_ProducerConsumer {
public static void main(String[] args) {
Resource r = new Resource();
Producer p = new Producer( r);
Consumer c = new Consumer( r);
new Thread( p).start();
new Thread( p).start();
new Thread( c).start();
new Thread( c).start();
}
}
class anonyThread {
public static void main(String[] args) {
new Thread( new Runnable() {
public void run() {
System. out.println("runnable run" );
}
}) {
public void run() {
System. out.println("subthread run" );// 执行。
}
}.start();
}
}
import java.util.Random;
class Demo implements Runnable {
public void run() {
for (int x = 1; x <= 10; x++) {
// 随机sleep一段时间
Random random = new Random();
int i = Math.abs(random .nextInt() % 100 + 1);
try {
Thread. sleep((long) i);
} catch (InterruptedException e) {
System. out.println("haha" );
e.printStackTrace();
}
// 输出语句
System.out.println(Thread. currentThread().getName() + "..." + x );
Thread.yield(); // 线程临时暂停。将执行权释放,让其他线程有机会获取执行权。
}
}
}
public class ThreadOthers {
public static void main(String[] args) {
// 线程的匿名内部类
new Thread( new Runnable() {
public void run() {
System. out.println("runnable run" );
}
}) {
public void run() {
System. out.println("subthread run" ); // 执行。
}
}.start();
Demo d = new Demo();
Thread t1 = new Thread( d);
Thread t2 = new Thread( d);
t1.start();
t2.start();
// 临时加入一个运算的线程。让该线程运算完,程序才会继续执行。
try {
t1.join();
} catch (InterruptedException e) {}
// 主线程执行到这里,直到t1要加入执行,主线程释放了执行权,执行资格并处于阻塞状态,直到t1线程执行完毕。
for (int x = 1; x <= 10; x++) {
System.out.println( "main..." + x );
}
System.out.println( "over");
}
}
标签:
原文地址:http://blog.csdn.net/u010388781/article/details/51167722