您的位置:首页 > 编程语言

写2个线程,一个打印1-52,一个打印A-Z,打印顺序是12A34B。。。(采用同步代码块和同步方法两种同步方法)

2015-09-11 10:57 453 查看
1.同步方法

package Synchronized;
/************************************同步方法****************************************/
public class PrintTest {
public static void main(String[] args)
{
Print p = new Print();
Thread t1 = new PrintNumber(p);
Thread t2 = new PrintWord(p);
t1.start();
t2.start();
}
}

class PrintNumber extends Thread {//打印数字线程
private Print p;

public PrintNumber(Print p) {
this.p = p;
}

public void run() {
for (int i = 0; i < 26; i++) {
p.printNumber();
}
}
}

class PrintWord extends Thread {//打印字母线程
private Print p;

public PrintWord(Print p) {
this.p = p;
}

public void run() {
for (int i = 0; i < 26; i++) {
p.printWord();
}
}
}

class Print {             //同步监视器是Print类
private int i = 1;
private char j = 'A';

public Print() {
}

public synchronized void printNumber() {//同步方法
System.out.print(String.valueOf(i) + String.valueOf(i + 1));
i += 2;
notifyAll();      //先唤醒其他进程,再阻塞本进程,如果顺序颠倒了,进程阻塞后不能再唤醒其他进程
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void printWord() {
System.out.print(j);
j++;
notifyAll();
try
{
if (j <= 'Z')//输出Z之后就不用再等待了。
{

wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}

}
}


2.同步代码块package threaddemo;

/**
* <写两个线程,一个线程打印1-52,另一个线程打印字母A-Z。打印 顺序为12A34B56C……5152Z>
*
*/
/*****************************************同步代码块*********************************************/
public class ThreadDemo
{
// 测试
public static void main(String[] args) throws Exception
{
Object obj = new Object();
// 启动两个线程
Thread1 t1 = new Thread1(obj);

Thread2 t2 = new Thread2(obj);

t1.start();
t2.start();
}

}

// 一个线程打印1-52
class Thread1 extends Thread
{
private Object obj;

public Thread1(Object obj)
{
this.obj = obj;
}

public void run()
{
synchronized (obj)
{
// 打印1-52
for (int i = 1; i < 53; i++)
{
System.out.print(i + " ");
if (i % 2 == 0)
{
// 不能忘了 唤醒其它线程
obj.notifyAll();
try
{
obj.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}

}

}

// 另一个线程打印字母A-Z
class Thread2 extends Thread
{
private Object obj;

public Thread2(Object obj)
{
this.obj = obj;
}

public void run()
{
synchronized (obj)             //同步监视器是obj类,同步代码块是写在run方法里面的。
{
// 打印A-Z
for (int i = 0; i < 26; i++)
{
System.out.print((char)('A' + i) + " ");
// 不能忘了 唤醒其它线程
obj.notifyAll();
try
{
// 最后一个就不要等了
if (i != 25)
{
obj.wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}

}

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: