67,513
社区成员
发帖
与我相关
我的任务
分享
public static volatile boolean flag=true;
public static void main(String[] args) {
for (int i=3;i<6;i++){
int finalI = i;
new Thread(()-> {
Data data = new Data();
while(data.getCount()<100&&nospringtest.flag){
synchronized (Thread.class){
if (!nospringtest.flag)
break;
data.setCount(data.getCount()+finalI);
System.out.println(Thread.currentThread().getName()+"跑了"+data.getCount()+"还有"+(100-data.getCount())+"米");
if(data.getCount()>=100){
System.out.println(Thread.currentThread().getName()+"跑完了");
nospringtest.flag=false;
return;
}
}
try {
TimeUnit.SECONDS.sleep(1);
}catch (Exception e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"跑了"+data.getCount()+"还有"+(100-data.getCount())+"米");
}).start();
}
}
public static void main(String[] args) {
Data data = new Data();
data.setCount(9);
for (int i=1;i<4;i++){
int finalI = i;
new Thread(()-> {
while(true){
if(data.getCount()< finalI){
System.out.println("不拿了");
return;
}
synchronized (data){
if(data.getCount()< finalI){
System.out.println("不拿了");
return;
}
data.setCount(data.getCount()-finalI);
System.out.println("拿到了个"+finalI+"橘子");
System.out.println("还有"+data.getCount());
}
try {
TimeUnit.SECONDS.sleep(finalI*1);
System.out.println("吃了"+finalI+"橘子");
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
}
class Data{
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
public static Node Merge(Node head1 , Node head2) {
Node node1;
Node node=new Node();
node1=node;
while(head1!=null&&head2!=null){
if(head1.data>head2.data){
node.next=head2;
node=node.next;
head2=head2.next;
}else{
node.next=head1;
node=node.next;
head1=head1.next;
}
}
if(head1==null)
node.next=head2;
if(head2==null)
node.next=head1;
return node1.next;
}
@Test
public void Testnode(){
Node node = new Node(new Node(new Node(5),4),3);
Node node1 = new Node(new Node(new Node(7),5),3);
Node merge = Merge(node, node1);
while (merge!=null){
System.out.println(merge.data);
merge=merge.next;
}
}
class Node{
int data;
Node next;
public Node(){}
public Node(int id){this.data=id;}
public Node(Node n,int id){this.next=n;this.data=id;}
}