首页 技术 正文
技术 2022年11月23日
0 收藏 453 点赞 4,568 浏览 951 个字

1、首先创建一个打印机对象

package cn.b.happy;public class Printer {
Object o =new Object();
public void print(){
synchronized(o){
System.out.print("微");
System.out.print("冷");
System.out.print("的");
System.out.print("雨");
System.out.println();
}
}public void print1(){
synchronized(o){
System.out.print("好");
System.out.print("人");
System.out.println();
}}}

  

2、创建两个线程分别为thread1 和 thread2 分别继承thread 和 是实现 runnable接口 包含 打印机 printer 对象

package cn.b.happy;public class MyThread1 extends Thread{    public Printer print;
@Override
public void run() {
for (int i = 1; i <=500; i++) {
print.print();
}
}
}
package cn.b.happy;public class MyThread2 implements Runnable {
public Printer print;
@Override
public void run() {
for (int i = 1; i <=500; i++) {
print.print1();
} }}

3、测试类  实现runnable 接口的 线程 不能调用start()方法,所以创建一个Thread线程对象里边传实现runnable接口的类,从而实现开启线程

package cn.b.happy;public class Test {
public static void main(String[] args) {
Printer p =new Printer();
MyThread1 t1 =new MyThread1();
t1.print=p;
t1.start(); MyThread2 t2 =new MyThread2();
t2.print=p;
Thread t=new Thread(t2);
t.start();
}}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,909
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,434
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,249
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,060
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,692
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,730