class MyThread3 implements Runnable{
//两个线程操作同一个对象,共享成员变量
//int i;
@Override
public void run() {
//两个线程操作同一个对象,各自保存局部变量的拷贝
int i = 0;
while(i<100){
System.out.println(i);
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyThread3 myThread = new MyThread3();
//下面两个线程对同一个对象(Runnable的实现类对象)进行操作
Thread thread = new Thread(myThread);
Thread thread2 = new Thread(myThread);
//各自保存局部变量的拷贝,互不影响,输出200个数字
thread.start();
thread2.start();
}
class Number{
private int number = 10;
public String getNumber(int i){
if(number > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
number -= i;
return "取出"+i+"成功,剩余数量:"+number;
}
return "取出"+i+"失败,剩余数量:"+number;
}
}
class MyThread4 extends Thread{
//两个线程操作同一个对象,共享成员变量
Number number;
public MyThread4(Number number){
this.number = number;
}
@Override
public void run() {
System.out.println(number.getNumber(8));
}
}
public static void main(String[] args) {
Number number = new Number();
//两个线程操作同一个对象,共享对象number的成员变量number
MyThread4 myThread = new MyThread4(number);
MyThread4 myThread2 = new MyThread4(number);
myThread.start();
myThread2.start();
}
/**
* 定义一个类,包含了线程类需要调用的方法
*/
class Compute1{
//这时如果某个线程调用该方法,
//将锁定synchronized方法所在对象对应的class对象,
//而不是锁定synchronized方法所在对象
public synchronized static void execute(){
for(int i = 0; i<100; i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("compute1:execute1 " + i++);
}
}
public synchronized static void execute2(){
for(int i = 0; i<100; i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("compute1:execute2 " + i++);
}
}
}
public static void main(String[] args) {
Compute1 com = new Compute1();
Thread thread1 = new Thread1(com);
Thread thread2 = new Thread2(com);
thread1.start();
thread2.start();
}
/**
* 定义一个类,包含了线程类需要调用的方法
*/
class Compute1{
//通过同步代码块锁定object1对象进行锁定了其他同样的synchronized代码块
private Object object1 = new Object();
public void execute(){
synchronized(object1){
for(int i = 0; i<100; i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("compute1:execute1 " + i++);
}
}
}
public synchronized void execute2(){
synchronized(object1){
for(int i = 0; i<100; i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("compute1:execute2 " + i++);
}
}
}
}
synchronized(this){
…
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有