我写的

class LN
{
private int flag = 0;
public static char ch = 'A';
public static int n = 1;
public synchronized void printLetter()
{
try
{
if(flag == 0 || flag == 1)
{
wait();
}
else
{
//System.out.println("flag = " + flag);
System.out.print(ch);
ch++; flag = (flag + 1) % 3; notifyAll();
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public synchronized void printNumber()
{
try
{
if(flag == 2 )
{
wait();
}
else
{
//System.out.println("flag = " + flag);
System.out.print(n);
n++; flag = (flag + 1) % 3; notifyAll();
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
} class Letter extends Thread
{
LN ln;
Letter(LN ln)
{
this.ln = ln;
}
public void run()
{
for(int i = 0 ; i< 26; i++)
{
ln.printLetter();
}
}
}
class Number extends Thread
{
LN ln;
Number(LN ln)
{
this.ln = ln;
}
public void run()
{
for(int i = 0 ; i< 78; i++)
{
ln.printNumber();
}
}
} class Practice1
{
public static void main(String[] args) { LN ln = new LN();
new Letter(ln).start();
new Number(ln).start();
}
}

网上找的

public class ThreadDemo {
// 测试
public static void main(String[] args) {
Object obj = new Object();
// 启动两个线程
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj); t1.start();
t2.start();
}
} 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();
}
}
} }
}
} class Thread2 extends Thread {
private Object obj; public Thread2(Object obj) {
this.obj = obj;
} public void run() {
synchronized (obj) {
// 打印A-Z
for (int i = 0; i < 26; i++) {
System.out.print((char) ('A' + i));
// 不能忘了唤醒其它线程
obj.notifyAll();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

最新文章

  1. SHOI2016游记&amp;滚粗记&amp;酱油记
  2. td标签内的内容过长导致的问题的解决办法
  3. 云计算之路-阿里云上:消灭“黑色n秒”第三招——禁用网卡的TCP/IP Offload
  4. 测试秒杀新版本3.5 stieserver cms
  5. atitit.j2ee 1.5 1.6 的不同跟 Servlet 3.0新特性总结
  6. 【转载】JS获取屏幕大小
  7. HDU1009老鼠的旅行 (贪心算法)
  8. angular--todomvc
  9. 转:eclipse技巧之快速生成Override函数
  10. 十月例题F题 - City Game
  11. linux打包/解压-tar
  12. dumpbin
  13. ToString() 格式化
  14. Struts2验证
  15. TurnipBit开发板掷骰子小游戏DIY教程实例
  16. Android NFC开发(一)——初探NFC,了解当前前沿技术
  17. 网络请求 Requests
  18. LVS负载均衡集群(DR)
  19. 【OCR技术系列之八】端到端不定长文本识别CRNN代码实现
  20. Cognos11中报XQE-JDB-0004查找驱动程序类错误

热门文章

  1. Dell Omsa在Linux服务器上安装部署
  2. 第42届亚洲区域赛青岛站(2017icpc青岛)经验总结以及一些感想
  3. android项目引入第三方库工程出现的问题及解决方案
  4. java第五章 子类与继承
  5. 九度oj 题目1214:丑数
  6. shit layui &amp; bugs
  7. P1651 塔 (动态规划)
  8. 动手实践 Linux VLAN
  9. DP的序--Codeforces626F. Group Projects
  10. 标准C程序设计七---06